| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | |
| | | 4 | | namespace NLightning.Application.Channels.Handlers; |
| | | 5 | | |
| | | 6 | | using Domain.Channels.Enums; |
| | | 7 | | using Domain.Channels.Interfaces; |
| | | 8 | | using Domain.Channels.Models; |
| | | 9 | | using Domain.Crypto.ValueObjects; |
| | | 10 | | using Domain.Enums; |
| | | 11 | | using Domain.Exceptions; |
| | | 12 | | using Domain.Node.Options; |
| | | 13 | | using Domain.Persistence.Interfaces; |
| | | 14 | | using Domain.Protocol.Interfaces; |
| | | 15 | | using Domain.Protocol.Messages; |
| | | 16 | | using Interfaces; |
| | | 17 | | |
| | | 18 | | public class ChannelReadyMessageHandler : IChannelMessageHandler<ChannelReadyMessage> |
| | | 19 | | { |
| | | 20 | | private readonly IChannelMemoryRepository _channelMemoryRepository; |
| | | 21 | | private readonly ILogger<ChannelReadyMessageHandler> _logger; |
| | | 22 | | private readonly IUnitOfWork _unitOfWork; |
| | | 23 | | |
| | 0 | 24 | | public ChannelReadyMessageHandler(IChannelMemoryRepository channelMemoryRepository, |
| | 0 | 25 | | ILogger<ChannelReadyMessageHandler> logger, IUnitOfWork unitOfWork) |
| | | 26 | | { |
| | 0 | 27 | | _channelMemoryRepository = channelMemoryRepository; |
| | 0 | 28 | | _logger = logger; |
| | 0 | 29 | | _unitOfWork = unitOfWork; |
| | 0 | 30 | | } |
| | | 31 | | |
| | | 32 | | public async Task<IChannelMessage?> HandleAsync(ChannelReadyMessage message, ChannelState currentState, |
| | | 33 | | FeatureOptions negotiatedFeatures, CompactPubKey peerPubKey) |
| | | 34 | | { |
| | 0 | 35 | | if (_logger.IsEnabled(LogLevel.Trace)) |
| | 0 | 36 | | _logger.LogTrace("Processing ChannelReadyMessage with ChannelId: {ChannelId} from Peer: {PeerPubKey}", |
| | 0 | 37 | | message.Payload.ChannelId, peerPubKey); |
| | | 38 | | |
| | 0 | 39 | | var payload = message.Payload; |
| | | 40 | | |
| | 0 | 41 | | if (currentState is not (ChannelState.V1FundingSigned |
| | 0 | 42 | | or ChannelState.ReadyForThem |
| | 0 | 43 | | or ChannelState.ReadyForUs |
| | 0 | 44 | | or ChannelState.Open)) |
| | 0 | 45 | | throw new ChannelErrorException( |
| | 0 | 46 | | $"Unexpected ChannelReady message in state {Enum.GetName(currentState)}", |
| | 0 | 47 | | payload.ChannelId, |
| | 0 | 48 | | "Protocol violation: unexpected ChannelReady message"); |
| | | 49 | | |
| | | 50 | | // Check if there's a channel for this peer |
| | 0 | 51 | | if (!_channelMemoryRepository.TryGetChannel(payload.ChannelId, out var channel)) |
| | 0 | 52 | | throw new ChannelErrorException("Channel not found", payload.ChannelId, |
| | 0 | 53 | | "This channel is not ready to be opened"); |
| | | 54 | | |
| | 0 | 55 | | var mustUseScidAlias = channel.ChannelConfig.UseScidAlias > FeatureSupport.No; |
| | 0 | 56 | | if (mustUseScidAlias && message.ShortChannelIdTlv is null) |
| | 0 | 57 | | throw new ChannelWarningException("No ShortChannelIdTlv provided", |
| | 0 | 58 | | payload.ChannelId, |
| | 0 | 59 | | "This channel requires a ShortChannelIdTlv to be provided"); |
| | | 60 | | |
| | | 61 | | // Store their new per-commitment point |
| | 0 | 62 | | if (channel.RemoteKeySet!.CurrentPerCommitmentIndex == 0) |
| | 0 | 63 | | channel.RemoteKeySet.UpdatePerCommitmentPoint(payload.SecondPerCommitmentPoint); |
| | | 64 | | |
| | | 65 | | switch (currentState) |
| | | 66 | | { |
| | | 67 | | case ChannelState.Open or ChannelState.ReadyForThem: // Handle ScidAlias |
| | | 68 | | { |
| | 0 | 69 | | if (mustUseScidAlias) |
| | | 70 | | { |
| | 0 | 71 | | if (ShouldReplaceAlias()) |
| | | 72 | | { |
| | 0 | 73 | | var oldAlias = channel.RemoteAlias; |
| | 0 | 74 | | channel.RemoteAlias = message.ShortChannelIdTlv!.ShortChannelId; |
| | | 75 | | |
| | 0 | 76 | | if (_logger.IsEnabled(LogLevel.Debug)) |
| | 0 | 77 | | _logger.LogDebug( |
| | 0 | 78 | | "Updated remote alias for channel {ChannelId} from {OldAlias} to {NewAlias}", |
| | 0 | 79 | | payload.ChannelId, oldAlias, channel.RemoteAlias); |
| | | 80 | | |
| | 0 | 81 | | await PersistChannelAsync(channel); |
| | | 82 | | } |
| | 0 | 83 | | else if (_logger.IsEnabled(LogLevel.Debug)) |
| | | 84 | | { |
| | 0 | 85 | | _logger.LogDebug( |
| | 0 | 86 | | "Keeping existing remote alias {ExistingAlias} for channel {ChannelId}", |
| | 0 | 87 | | channel.RemoteAlias, |
| | 0 | 88 | | payload.ChannelId); |
| | | 89 | | } |
| | | 90 | | } |
| | 0 | 91 | | else if (_logger.IsEnabled(LogLevel.Debug)) |
| | 0 | 92 | | _logger.LogDebug("Received duplicate ChannelReady message for channel {ChannelId} in Open state" |
| | 0 | 93 | | payload.ChannelId); |
| | | 94 | | |
| | 0 | 95 | | break; |
| | | 96 | | } |
| | | 97 | | case ChannelState.ReadyForUs: // We already sent our ChannelReady, now they sent theirs |
| | | 98 | | { |
| | | 99 | | // Valid transition: ReadyForUs -> Open |
| | 0 | 100 | | channel.UpdateState(ChannelState.Open); |
| | 0 | 101 | | await PersistChannelAsync(channel); |
| | | 102 | | |
| | 0 | 103 | | if (_logger.IsEnabled(LogLevel.Information)) |
| | 0 | 104 | | _logger.LogInformation("Channel {ChannelId} is now open", payload.ChannelId); |
| | | 105 | | |
| | | 106 | | // TODO: Notify application layer that channel is fully open |
| | | 107 | | // TODO: Update routing tables |
| | | 108 | | |
| | 0 | 109 | | break; |
| | | 110 | | } |
| | | 111 | | case ChannelState.V1FundingSigned: // First ChannelReady |
| | | 112 | | { |
| | | 113 | | // Valid transition: V1FundingSigned -> ReadyForThem |
| | 0 | 114 | | channel.UpdateState(ChannelState.ReadyForThem); |
| | 0 | 115 | | await PersistChannelAsync(channel); |
| | | 116 | | |
| | 0 | 117 | | if (_logger.IsEnabled(LogLevel.Information)) |
| | 0 | 118 | | _logger.LogInformation( |
| | 0 | 119 | | "Received ChannelReady from peer for channel {ChannelId}, waiting for funding confirmation", |
| | 0 | 120 | | payload.ChannelId); |
| | | 121 | | |
| | | 122 | | break; |
| | | 123 | | } |
| | | 124 | | } |
| | | 125 | | |
| | 0 | 126 | | return null; // No further action needed |
| | 0 | 127 | | } |
| | | 128 | | |
| | | 129 | | /// <summary> |
| | | 130 | | /// Persists a channel to the database using a scoped Unit of Work |
| | | 131 | | /// </summary> |
| | | 132 | | private async Task PersistChannelAsync(ChannelModel channel) |
| | | 133 | | { |
| | | 134 | | try |
| | | 135 | | { |
| | | 136 | | // Check if the channel already exists |
| | 0 | 137 | | _ = await _unitOfWork.ChannelDbRepository.GetByIdAsync(channel.ChannelId) |
| | 0 | 138 | | ?? throw new ChannelWarningException("Channel not found in database", channel.ChannelId, |
| | 0 | 139 | | "Sorry, we had an internal error"); |
| | 0 | 140 | | await _unitOfWork.ChannelDbRepository.UpdateAsync(channel); |
| | 0 | 141 | | await _unitOfWork.SaveChangesAsync(); |
| | | 142 | | |
| | 0 | 143 | | _channelMemoryRepository.UpdateChannel(channel); |
| | | 144 | | |
| | 0 | 145 | | if (_logger.IsEnabled(LogLevel.Debug)) |
| | 0 | 146 | | _logger.LogDebug("Successfully persisted channel {ChannelId} to database", channel.ChannelId); |
| | 0 | 147 | | } |
| | 0 | 148 | | catch (Exception ex) |
| | | 149 | | { |
| | 0 | 150 | | _logger.LogError(ex, "Failed to persist channel {ChannelId} to database", channel.ChannelId); |
| | 0 | 151 | | throw; |
| | | 152 | | } |
| | 0 | 153 | | } |
| | | 154 | | |
| | | 155 | | private static bool ShouldReplaceAlias() |
| | | 156 | | { |
| | 0 | 157 | | return RandomNumberGenerator.GetInt32(0, 2) switch |
| | 0 | 158 | | { |
| | 0 | 159 | | 0 => true, |
| | 0 | 160 | | _ => false |
| | 0 | 161 | | }; |
| | | 162 | | } |
| | | 163 | | } |