| | 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 | | _logger.LogTrace("Processing ChannelReadyMessage with ChannelId: {ChannelId} from Peer: {PeerPubKey}", |
| 0 | 36 | | message.Payload.ChannelId, peerPubKey); |
| | 37 | |
|
| 0 | 38 | | var payload = message.Payload; |
| | 39 | |
|
| 0 | 40 | | if (currentState is not (ChannelState.V1FundingSigned |
| 0 | 41 | | or ChannelState.ReadyForThem |
| 0 | 42 | | or ChannelState.ReadyForUs |
| 0 | 43 | | or ChannelState.Open)) |
| 0 | 44 | | throw new ChannelErrorException("Channel had the wrong state", payload.ChannelId, |
| 0 | 45 | | "This channel is not ready to be opened"); |
| | 46 | |
|
| | 47 | | // Check if there's a channel for this peer |
| 0 | 48 | | if (!_channelMemoryRepository.TryGetChannel(payload.ChannelId, out var channel)) |
| 0 | 49 | | throw new ChannelErrorException("Channel not found", payload.ChannelId, |
| 0 | 50 | | "This channel is not ready to be opened"); |
| | 51 | |
|
| 0 | 52 | | var mustUseScidAlias = channel.ChannelConfig.UseScidAlias > FeatureSupport.No; |
| 0 | 53 | | if (mustUseScidAlias && message.ShortChannelIdTlv is null) |
| 0 | 54 | | throw new ChannelWarningException("No ShortChannelIdTlv provided", |
| 0 | 55 | | payload.ChannelId, |
| 0 | 56 | | "This channel requires a ShortChannelIdTlv to be provided"); |
| | 57 | |
|
| | 58 | | // Store their new per-commitment point |
| 0 | 59 | | if (channel.RemoteKeySet.CurrentPerCommitmentIndex == 0) |
| 0 | 60 | | channel.RemoteKeySet.UpdatePerCommitmentPoint(payload.SecondPerCommitmentPoint); |
| | 61 | |
|
| | 62 | | // Handle ScidAlias |
| 0 | 63 | | if (currentState is ChannelState.Open or ChannelState.ReadyForThem) |
| | 64 | | { |
| 0 | 65 | | if (mustUseScidAlias) |
| | 66 | | { |
| 0 | 67 | | if (ShouldReplaceAlias()) |
| | 68 | | { |
| 0 | 69 | | var oldAlias = channel.RemoteAlias; |
| 0 | 70 | | channel.RemoteAlias = message.ShortChannelIdTlv!.ShortChannelId; |
| | 71 | |
|
| 0 | 72 | | _logger.LogDebug("Updated remote alias for channel {ChannelId} from {OldAlias} to {NewAlias}", |
| 0 | 73 | | payload.ChannelId, oldAlias, channel.RemoteAlias); |
| | 74 | |
|
| 0 | 75 | | await PersistChannelAsync(channel); |
| | 76 | | } |
| | 77 | | else |
| | 78 | | { |
| 0 | 79 | | _logger.LogDebug( |
| 0 | 80 | | "Keeping existing remote alias {ExistingAlias} for channel {ChannelId}", channel.RemoteAlias, |
| 0 | 81 | | payload.ChannelId); |
| | 82 | | } |
| | 83 | | } |
| | 84 | | else |
| 0 | 85 | | _logger.LogDebug("Received duplicate ChannelReady message for channel {ChannelId} in Open state", |
| 0 | 86 | | payload.ChannelId); |
| | 87 | |
|
| 0 | 88 | | return null; // No further action needed, we are already open |
| | 89 | | } |
| | 90 | |
|
| 0 | 91 | | if (channel.IsInitiator) // Handle state transitions based on whether we are the initiator |
| | 92 | | { |
| | 93 | | // We already sent our ChannelReady, now they sent theirs |
| 0 | 94 | | if (currentState == ChannelState.ReadyForUs) |
| | 95 | | { |
| | 96 | | // Valid transition: ReadyForUs -> Open |
| 0 | 97 | | channel.UpdateState(ChannelState.Open); |
| 0 | 98 | | await PersistChannelAsync(channel); |
| | 99 | |
|
| 0 | 100 | | _logger.LogInformation("Channel {ChannelId} is now open (we are initiator)", payload.ChannelId); |
| | 101 | |
|
| | 102 | | // TODO: Notify application layer that channel is fully open |
| | 103 | | // TODO: Update routing tables |
| | 104 | |
|
| 0 | 105 | | return null; |
| | 106 | | } |
| | 107 | |
|
| | 108 | | // Invalid state for initiator receiving ChannelReady |
| 0 | 109 | | _logger.LogError( |
| 0 | 110 | | "Received ChannelReady message for channel {ChannelId} in invalid state {CurrentState} (we are initiator |
| 0 | 111 | | payload.ChannelId, currentState); |
| | 112 | |
|
| 0 | 113 | | throw new ChannelErrorException($"Unexpected ChannelReady message in state {Enum.GetName(currentState)}", |
| 0 | 114 | | payload.ChannelId, |
| 0 | 115 | | "Protocol violation: unexpected ChannelReady message"); |
| | 116 | | } |
| | 117 | |
|
| 0 | 118 | | if (currentState == ChannelState.V1FundingSigned) // We are not the initiator |
| | 119 | | { |
| | 120 | | // First ChannelReady from initiator |
| | 121 | | // Valid transition: V1FundingSigned -> ReadyForThem |
| 0 | 122 | | channel.UpdateState(ChannelState.ReadyForThem); |
| 0 | 123 | | await PersistChannelAsync(channel); |
| | 124 | |
|
| 0 | 125 | | _logger.LogInformation( |
| 0 | 126 | | "Received ChannelReady from initiator for channel {ChannelId}, waiting for funding confirmation", |
| 0 | 127 | | payload.ChannelId); |
| | 128 | |
|
| 0 | 129 | | return null; |
| | 130 | | } |
| | 131 | |
|
| | 132 | | // Invalid state for non-initiator receiving ChannelReady |
| 0 | 133 | | _logger.LogError( |
| 0 | 134 | | "Received ChannelReady message for channel {ChannelId} in invalid state {CurrentState} (we are not initiator |
| 0 | 135 | | payload.ChannelId, currentState); |
| | 136 | |
|
| 0 | 137 | | throw new ChannelErrorException($"Unexpected ChannelReady message in state {Enum.GetName(currentState)}", |
| 0 | 138 | | payload.ChannelId, |
| 0 | 139 | | "Protocol violation: unexpected ChannelReady message"); |
| 0 | 140 | | } |
| | 141 | |
|
| | 142 | | /// <summary> |
| | 143 | | /// Persists a channel to the database using a scoped Unit of Work |
| | 144 | | /// </summary> |
| | 145 | | private async Task PersistChannelAsync(ChannelModel channel) |
| | 146 | | { |
| | 147 | | try |
| | 148 | | { |
| | 149 | | // Check if the channel already exists |
| 0 | 150 | | _ = await _unitOfWork.ChannelDbRepository.GetByIdAsync(channel.ChannelId) |
| 0 | 151 | | ?? throw new ChannelWarningException("Channel not found in database", channel.ChannelId, |
| 0 | 152 | | "Sorry, we had an internal error"); |
| 0 | 153 | | await _unitOfWork.ChannelDbRepository.UpdateAsync(channel); |
| 0 | 154 | | await _unitOfWork.SaveChangesAsync(); |
| | 155 | |
|
| 0 | 156 | | _channelMemoryRepository.UpdateChannel(channel); |
| | 157 | |
|
| 0 | 158 | | _logger.LogDebug("Successfully persisted channel {ChannelId} to database", channel.ChannelId); |
| 0 | 159 | | } |
| 0 | 160 | | catch (Exception ex) |
| | 161 | | { |
| 0 | 162 | | _logger.LogError(ex, "Failed to persist channel {ChannelId} to database", channel.ChannelId); |
| 0 | 163 | | throw; |
| | 164 | | } |
| 0 | 165 | | } |
| | 166 | |
|
| | 167 | | private static bool ShouldReplaceAlias() |
| | 168 | | { |
| 0 | 169 | | return RandomNumberGenerator.GetInt32(0, 2) switch |
| 0 | 170 | | { |
| 0 | 171 | | 0 => true, |
| 0 | 172 | | _ => false |
| 0 | 173 | | }; |
| | 174 | | } |
| | 175 | | } |