| | 1 | | using Microsoft.Extensions.DependencyInjection; |
| | 2 | | using Microsoft.Extensions.Logging; |
| | 3 | |
|
| | 4 | | namespace NLightning.Application.Channels.Managers; |
| | 5 | |
|
| | 6 | | using Domain.Bitcoin.Events; |
| | 7 | | using Domain.Bitcoin.Interfaces; |
| | 8 | | using Domain.Channels.Constants; |
| | 9 | | using Domain.Channels.Enums; |
| | 10 | | using Domain.Channels.Events; |
| | 11 | | using Domain.Channels.Interfaces; |
| | 12 | | using Domain.Channels.Models; |
| | 13 | | using Domain.Channels.ValueObjects; |
| | 14 | | using Domain.Crypto.ValueObjects; |
| | 15 | | using Domain.Exceptions; |
| | 16 | | using Domain.Node.Options; |
| | 17 | | using Domain.Persistence.Interfaces; |
| | 18 | | using Domain.Protocol.Constants; |
| | 19 | | using Domain.Protocol.Interfaces; |
| | 20 | | using Domain.Protocol.Messages; |
| | 21 | | using Handlers; |
| | 22 | | using Handlers.Interfaces; |
| | 23 | | using Infrastructure.Bitcoin.Wallet.Interfaces; |
| | 24 | |
|
| | 25 | | public class ChannelManager : IChannelManager |
| | 26 | | { |
| | 27 | | private readonly IChannelMemoryRepository _channelMemoryRepository; |
| | 28 | | private readonly ILogger<ChannelManager> _logger; |
| | 29 | | private readonly ILightningSigner _lightningSigner; |
| | 30 | | private readonly IServiceProvider _serviceProvider; |
| | 31 | |
|
| | 32 | | public event EventHandler<ChannelResponseMessageEventArgs>? OnResponseMessageReady; |
| | 33 | |
|
| 0 | 34 | | public ChannelManager(IBlockchainMonitor blockchainMonitor, IChannelMemoryRepository channelMemoryRepository, |
| 0 | 35 | | ILogger<ChannelManager> logger, ILightningSigner lightningSigner, |
| 0 | 36 | | IServiceProvider serviceProvider) |
| | 37 | | { |
| 0 | 38 | | _channelMemoryRepository = channelMemoryRepository; |
| 0 | 39 | | _serviceProvider = serviceProvider; |
| 0 | 40 | | _logger = logger; |
| 0 | 41 | | _lightningSigner = lightningSigner; |
| | 42 | |
|
| 0 | 43 | | blockchainMonitor.OnNewBlockDetected += HandleNewBlockDetected; |
| 0 | 44 | | blockchainMonitor.OnTransactionConfirmed += HandleFundingConfirmationAsync; |
| 0 | 45 | | } |
| | 46 | |
|
| | 47 | | public Task RegisterExistingChannelAsync(ChannelModel channel) |
| | 48 | | { |
| 0 | 49 | | ArgumentNullException.ThrowIfNull(channel); |
| | 50 | |
|
| | 51 | | // Add the channel to the memory repository |
| 0 | 52 | | _channelMemoryRepository.AddChannel(channel); |
| | 53 | |
|
| | 54 | | // Register the channel with the signer |
| 0 | 55 | | _lightningSigner.RegisterChannel(channel.ChannelId, channel.GetSigningInfo()); |
| | 56 | |
|
| 0 | 57 | | _logger.LogInformation("Loaded channel {channelId} from database", channel.ChannelId); |
| | 58 | |
|
| | 59 | | // If the channel is open and ready |
| 0 | 60 | | if (channel.State == ChannelState.Open) |
| | 61 | | { |
| | 62 | | // TODO: Check if the channel has already been reestablished or if we need to reestablish it |
| | 63 | | } |
| 0 | 64 | | else if (channel.State is ChannelState.ReadyForThem or ChannelState.ReadyForUs) |
| | 65 | | { |
| 0 | 66 | | _logger.LogInformation("Waiting for channel {ChannelId} to be ready", channel.ChannelId); |
| | 67 | | } |
| | 68 | | else |
| | 69 | | { |
| | 70 | | // TODO: Deal with channels that are Closing, Stale, or any other state |
| 0 | 71 | | _logger.LogWarning("We don't know how to deal with {channelState} for channel {ChannelId}", |
| 0 | 72 | | Enum.GetName(channel.State), channel.ChannelId); |
| | 73 | | } |
| | 74 | |
|
| 0 | 75 | | return Task.CompletedTask; |
| | 76 | | } |
| | 77 | |
|
| | 78 | | public async Task<IChannelMessage?> HandleChannelMessageAsync(IChannelMessage message, |
| | 79 | | FeatureOptions negotiatedFeatures, |
| | 80 | | CompactPubKey peerPubKey) |
| | 81 | | { |
| 0 | 82 | | using var scope = _serviceProvider.CreateScope(); |
| | 83 | |
|
| | 84 | | // Check if the channel exists on the state dictionary |
| 0 | 85 | | _channelMemoryRepository.TryGetChannelState(message.Payload.ChannelId, out var currentState); |
| | 86 | |
|
| | 87 | | // In this case we can only handle messages that are opening a channel |
| 0 | 88 | | switch (message.Type) |
| | 89 | | { |
| | 90 | | case MessageTypes.OpenChannel: |
| | 91 | | // Handle opening channel message |
| 0 | 92 | | var openChannel1Message = message as OpenChannel1Message |
| 0 | 93 | | ?? throw new ChannelErrorException("Error boxing message to OpenChannel1Message", |
| 0 | 94 | | "Sorry, we had an internal error"); |
| 0 | 95 | | return await GetChannelMessageHandler<OpenChannel1Message>(scope) |
| 0 | 96 | | .HandleAsync(openChannel1Message, currentState, negotiatedFeatures, peerPubKey); |
| | 97 | |
|
| | 98 | | case MessageTypes.FundingCreated: |
| | 99 | | // Handle the funding-created message |
| 0 | 100 | | var fundingCreatedMessage = message as FundingCreatedMessage |
| 0 | 101 | | ?? throw new ChannelErrorException( |
| 0 | 102 | | "Error boxing message to FundingCreatedMessage", |
| 0 | 103 | | "Sorry, we had an internal error"); |
| 0 | 104 | | return await GetChannelMessageHandler<FundingCreatedMessage>(scope) |
| 0 | 105 | | .HandleAsync(fundingCreatedMessage, currentState, negotiatedFeatures, peerPubKey); |
| | 106 | |
|
| | 107 | | case MessageTypes.ChannelReady: |
| | 108 | | // Handle channel ready message |
| 0 | 109 | | var channelReadyMessage = message as ChannelReadyMessage |
| 0 | 110 | | ?? throw new ChannelErrorException("Error boxing message to ChannelReadyMessage", |
| 0 | 111 | | "Sorry, we had an internal error"); |
| 0 | 112 | | return await GetChannelMessageHandler<ChannelReadyMessage>(scope) |
| 0 | 113 | | .HandleAsync(channelReadyMessage, currentState, negotiatedFeatures, peerPubKey); |
| | 114 | | default: |
| 0 | 115 | | throw new ChannelErrorException("Unknown message type", "Sorry, we had an internal error"); |
| | 116 | | } |
| 0 | 117 | | } |
| | 118 | |
|
| | 119 | | private IChannelMessageHandler<T> GetChannelMessageHandler<T>(IServiceScope scope) |
| | 120 | | where T : IChannelMessage |
| | 121 | | { |
| 0 | 122 | | var handler = scope.ServiceProvider.GetRequiredService<IChannelMessageHandler<T>>() ?? |
| 0 | 123 | | throw new ChannelErrorException($"No handler found for message type {typeof(T).FullName}", |
| 0 | 124 | | "Sorry, we had an internal error"); |
| 0 | 125 | | return handler; |
| | 126 | | } |
| | 127 | |
|
| | 128 | | /// <summary> |
| | 129 | | /// Persists a channel to the database using a scoped Unit of Work |
| | 130 | | /// </summary> |
| | 131 | | private async Task PersistChannelAsync(ChannelModel channel) |
| | 132 | | { |
| 0 | 133 | | using var scope = _serviceProvider.CreateScope(); |
| 0 | 134 | | var unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| | 135 | |
|
| | 136 | | try |
| | 137 | | { |
| | 138 | | // Check if the channel already exists |
| | 139 | |
|
| 0 | 140 | | _ = await unitOfWork.ChannelDbRepository.GetByIdAsync(channel.ChannelId) |
| 0 | 141 | | ?? throw new ChannelWarningException("Channel not found", channel.ChannelId); |
| 0 | 142 | | await unitOfWork.ChannelDbRepository.UpdateAsync(channel); |
| 0 | 143 | | await unitOfWork.SaveChangesAsync(); |
| | 144 | |
|
| | 145 | | // Remove from dictionaries |
| 0 | 146 | | _channelMemoryRepository.RemoveChannel(channel.ChannelId); |
| | 147 | |
|
| 0 | 148 | | _logger.LogDebug("Successfully persisted channel {ChannelId} to database", channel.ChannelId); |
| 0 | 149 | | } |
| 0 | 150 | | catch (Exception ex) |
| | 151 | | { |
| 0 | 152 | | _logger.LogError(ex, "Failed to persist channel {ChannelId} to database", channel.ChannelId); |
| 0 | 153 | | throw; |
| | 154 | | } |
| 0 | 155 | | } |
| | 156 | |
|
| | 157 | | private void HandleNewBlockDetected(object? sender, NewBlockEventArgs args) |
| | 158 | | { |
| 0 | 159 | | ArgumentNullException.ThrowIfNull(args); |
| | 160 | |
|
| 0 | 161 | | var currentHeight = (int)args.Height; |
| | 162 | |
|
| | 163 | | // Deal with stale channels |
| 0 | 164 | | ForgetStaleChannels(currentHeight); |
| | 165 | |
|
| | 166 | | // Deal with channels that are waiting for funding confirmation on start-up |
| 0 | 167 | | ConfirmUnconfirmedChannels(currentHeight); |
| 0 | 168 | | } |
| | 169 | |
|
| | 170 | | private void ForgetStaleChannels(int currentHeight) |
| | 171 | | { |
| 0 | 172 | | var heightLimit = currentHeight - ChannelConstants.MaxUnconfirmedChannelAge; |
| 0 | 173 | | if (heightLimit < 0) |
| | 174 | | { |
| 0 | 175 | | _logger.LogDebug("Block height {BlockHeight} is too low to forget channels", currentHeight); |
| 0 | 176 | | return; |
| | 177 | | } |
| | 178 | |
|
| 0 | 179 | | var staleChannels = _channelMemoryRepository.FindChannels(c => c.FundingCreatedAtBlockHeight <= heightLimit); |
| | 180 | |
|
| 0 | 181 | | _logger.LogDebug( |
| 0 | 182 | | "Forgetting stale channels created before block height {HeightLimit}, found {StaleChannelCount} channels", |
| 0 | 183 | | heightLimit, staleChannels.Count); |
| | 184 | |
|
| 0 | 185 | | foreach (var staleChannel in staleChannels) |
| | 186 | | { |
| 0 | 187 | | _logger.LogInformation( |
| 0 | 188 | | "Forgetting stale channel {ChannelId} with funding created at block height {BlockHeight}", |
| 0 | 189 | | staleChannel.ChannelId, staleChannel.FundingCreatedAtBlockHeight); |
| | 190 | |
|
| | 191 | | // Set states |
| 0 | 192 | | staleChannel.UpdateState(ChannelState.Stale); |
| 0 | 193 | | _channelMemoryRepository.UpdateChannel(staleChannel); |
| | 194 | |
|
| | 195 | | // Persist on Db |
| | 196 | | try |
| | 197 | | { |
| 0 | 198 | | PersistChannelAsync(staleChannel).ContinueWith(task => |
| 0 | 199 | | { |
| 0 | 200 | | _logger.LogError(task.Exception, "Error while marking channel {channelId} as stale.", |
| 0 | 201 | | staleChannel.ChannelId); |
| 0 | 202 | | }, TaskContinuationOptions.OnlyOnFaulted); |
| 0 | 203 | | } |
| 0 | 204 | | catch (Exception e) |
| | 205 | | { |
| 0 | 206 | | _logger.LogError(e, "Failed to persist stale channel {ChannelId} to database at height {currentHeight}", |
| 0 | 207 | | staleChannel.ChannelId, currentHeight); |
| 0 | 208 | | } |
| | 209 | | } |
| 0 | 210 | | } |
| | 211 | |
|
| | 212 | | private void ConfirmUnconfirmedChannels(int currentHeight) |
| | 213 | | { |
| 0 | 214 | | using var scope = _serviceProvider.CreateScope(); |
| 0 | 215 | | using var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| | 216 | |
|
| | 217 | | // Try to fetch the channel from memory |
| 0 | 218 | | var unconfirmedChannels = |
| 0 | 219 | | _channelMemoryRepository.FindChannels(c => c.State is ChannelState.ReadyForThem or ChannelState.ReadyForUs); |
| | 220 | |
|
| 0 | 221 | | foreach (var unconfirmedChannel in unconfirmedChannels) |
| | 222 | | { |
| | 223 | | // If the channel was created before the current block height, we can consider it confirmed |
| 0 | 224 | | if (unconfirmedChannel.FundingCreatedAtBlockHeight <= currentHeight) |
| | 225 | | { |
| 0 | 226 | | if (unconfirmedChannel.FundingOutput.TransactionId is null) |
| | 227 | | { |
| 0 | 228 | | _logger.LogError("Channel {ChannelId} has no funding transaction Id, cannot confirm", |
| 0 | 229 | | unconfirmedChannel.ChannelId); |
| 0 | 230 | | continue; |
| | 231 | | } |
| | 232 | |
|
| 0 | 233 | | var watchedTransaction = |
| 0 | 234 | | uow.WatchedTransactionDbRepository.GetByTransactionIdAsync( |
| 0 | 235 | | unconfirmedChannel.FundingOutput.TransactionId.Value).GetAwaiter().GetResult(); |
| 0 | 236 | | if (watchedTransaction is null) |
| | 237 | | { |
| 0 | 238 | | _logger.LogError("Watched transaction for channel {ChannelId} not found", |
| 0 | 239 | | unconfirmedChannel.ChannelId); |
| 0 | 240 | | continue; |
| | 241 | | } |
| | 242 | |
|
| | 243 | | // Create a TransactionConfirmedEventArgs and call the event handler |
| 0 | 244 | | var args = new TransactionConfirmedEventArgs(watchedTransaction, (uint)currentHeight); |
| 0 | 245 | | HandleFundingConfirmationAsync(this, args); |
| | 246 | | } |
| | 247 | | } |
| 0 | 248 | | } |
| | 249 | |
|
| | 250 | | private void HandleFundingConfirmationAsync(object? sender, TransactionConfirmedEventArgs args) |
| | 251 | | { |
| 0 | 252 | | ArgumentNullException.ThrowIfNull(args); |
| 0 | 253 | | if (args.WatchedTransaction.FirstSeenAtHeight is null) |
| | 254 | | { |
| 0 | 255 | | _logger.LogError( |
| 0 | 256 | | "Received null {nameof_FirstSeenAtHeight} in {nameof_TransactionConfirmedEventArgs} for channel {Channel |
| 0 | 257 | | nameof(args.WatchedTransaction.FirstSeenAtHeight), nameof(TransactionConfirmedEventArgs), |
| 0 | 258 | | args.WatchedTransaction.ChannelId); |
| 0 | 259 | | return; |
| | 260 | | } |
| | 261 | |
|
| 0 | 262 | | if (args.WatchedTransaction.TransactionIndex is null) |
| | 263 | | { |
| 0 | 264 | | _logger.LogError( |
| 0 | 265 | | "Received null {nameof_FirstSeenAtHeight} in {nameof_TransactionConfirmedEventArgs} for channel {Channel |
| 0 | 266 | | nameof(args.WatchedTransaction.FirstSeenAtHeight), nameof(TransactionConfirmedEventArgs), |
| 0 | 267 | | args.WatchedTransaction.ChannelId); |
| 0 | 268 | | return; |
| | 269 | | } |
| | 270 | |
|
| | 271 | | // Create a scope to handle the funding confirmation |
| 0 | 272 | | var scope = _serviceProvider.CreateScope(); |
| | 273 | |
|
| 0 | 274 | | var channelId = args.WatchedTransaction.ChannelId; |
| | 275 | | // Check if the transaction is a funding transaction for any channel |
| 0 | 276 | | if (!_channelMemoryRepository.TryGetChannel(channelId, out var channel)) |
| | 277 | | { |
| | 278 | | // Channel not found in memory, check the database |
| 0 | 279 | | var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>(); |
| 0 | 280 | | channel = uow.ChannelDbRepository.GetByIdAsync(channelId).GetAwaiter().GetResult(); |
| 0 | 281 | | if (channel is null) |
| | 282 | | { |
| 0 | 283 | | _logger.LogError("Funding confirmation for unknown channel {ChannelId}", channelId); |
| 0 | 284 | | return; |
| | 285 | | } |
| | 286 | |
|
| 0 | 287 | | _lightningSigner.RegisterChannel(channelId, channel.GetSigningInfo()); |
| 0 | 288 | | _channelMemoryRepository.AddChannel(channel); |
| | 289 | | } |
| | 290 | |
|
| 0 | 291 | | var fundingConfirmedHandler = scope.ServiceProvider.GetRequiredService<FundingConfirmedHandler>(); |
| | 292 | |
|
| | 293 | | // If we get a response, raise the event with the message |
| 0 | 294 | | fundingConfirmedHandler.OnMessageReady += (_, message) => |
| 0 | 295 | | OnResponseMessageReady?.Invoke(this, new ChannelResponseMessageEventArgs(channel.RemoteNodeId, message)); |
| | 296 | |
|
| | 297 | | // Add confirmation information to the channel |
| 0 | 298 | | channel.FundingCreatedAtBlockHeight = args.WatchedTransaction.FirstSeenAtHeight.Value; |
| 0 | 299 | | channel.ShortChannelId = new ShortChannelId(args.WatchedTransaction.FirstSeenAtHeight.Value, |
| 0 | 300 | | args.WatchedTransaction.TransactionIndex.Value, |
| 0 | 301 | | channel.FundingOutput.Index!.Value); |
| | 302 | |
|
| 0 | 303 | | fundingConfirmedHandler.HandleAsync(channel).ContinueWith(task => |
| 0 | 304 | | { |
| 0 | 305 | | if (task.IsFaulted) |
| 0 | 306 | | _logger.LogError(task.Exception, "Error while handling funding confirmation for channel {channelId}", |
| 0 | 307 | | channel.ChannelId); |
| 0 | 308 | |
|
| 0 | 309 | | scope.Dispose(); |
| 0 | 310 | | }); |
| 0 | 311 | | } |
| | 312 | | } |