| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | |
| | | 3 | | namespace NLightning.Daemon.Handlers; |
| | | 4 | | |
| | | 5 | | using Domain.Bitcoin.Interfaces; |
| | | 6 | | using Domain.Channels.Events; |
| | | 7 | | using Domain.Channels.Interfaces; |
| | | 8 | | using Domain.Channels.ValueObjects; |
| | | 9 | | using Domain.Client.Constants; |
| | | 10 | | using Domain.Client.Enums; |
| | | 11 | | using Domain.Client.Exceptions; |
| | | 12 | | using Domain.Client.Requests; |
| | | 13 | | using Domain.Client.Responses; |
| | | 14 | | using Domain.Crypto.ValueObjects; |
| | | 15 | | using Domain.Enums; |
| | | 16 | | using Domain.Exceptions; |
| | | 17 | | using Domain.Node; |
| | | 18 | | using Domain.Node.Events; |
| | | 19 | | using Domain.Node.Interfaces; |
| | | 20 | | using Domain.Node.ValueObjects; |
| | | 21 | | using Domain.Protocol.Interfaces; |
| | | 22 | | using Domain.Protocol.Tlv; |
| | | 23 | | using Infrastructure.Bitcoin.Wallet.Interfaces; |
| | | 24 | | using Infrastructure.Protocol.Models; |
| | | 25 | | using Interfaces; |
| | | 26 | | |
| | | 27 | | public sealed class OpenChannelClientHandler |
| | | 28 | | : IClientCommandHandler<OpenChannelClientRequest, OpenChannelClientResponse> |
| | | 29 | | { |
| | | 30 | | private readonly IBlockchainMonitor _blockchainMonitor; |
| | | 31 | | private readonly IChannelMemoryRepository _channelMemoryRepository; |
| | | 32 | | private readonly IChannelFactory _channelFactory; |
| | | 33 | | private readonly ILogger<OpenChannelClientHandler> _logger; |
| | | 34 | | private readonly IMessageFactory _messageFactory; |
| | | 35 | | private readonly IPeerManager _peerManager; |
| | | 36 | | private readonly IUtxoMemoryRepository _utxoMemoryRepository; |
| | | 37 | | |
| | 0 | 38 | | private ChannelId _channelId = ChannelId.Zero; |
| | | 39 | | private IPeerService? _peerService; |
| | | 40 | | |
| | | 41 | | /// <inheritdoc/> |
| | 0 | 42 | | public ClientCommand Command => ClientCommand.OpenChannel; |
| | | 43 | | |
| | 0 | 44 | | public OpenChannelClientHandler(IBlockchainMonitor blockchainMonitor, IChannelFactory channelFactory, |
| | 0 | 45 | | IChannelMemoryRepository channelMemoryRepository, |
| | 0 | 46 | | ILogger<OpenChannelClientHandler> logger, IMessageFactory messageFactory, |
| | 0 | 47 | | IPeerManager peerManager, IUtxoMemoryRepository utxoMemoryRepository) |
| | | 48 | | { |
| | 0 | 49 | | _blockchainMonitor = blockchainMonitor; |
| | 0 | 50 | | _channelFactory = channelFactory; |
| | 0 | 51 | | _channelMemoryRepository = channelMemoryRepository; |
| | 0 | 52 | | _logger = logger; |
| | 0 | 53 | | _messageFactory = messageFactory; |
| | 0 | 54 | | _peerManager = peerManager; |
| | 0 | 55 | | _utxoMemoryRepository = utxoMemoryRepository; |
| | 0 | 56 | | } |
| | | 57 | | |
| | | 58 | | /// <inheritdoc/> |
| | | 59 | | public async Task<OpenChannelClientResponse> HandleAsync(OpenChannelClientRequest request, CancellationToken ct) |
| | | 60 | | { |
| | 0 | 61 | | if (string.IsNullOrWhiteSpace(request.NodeInfo)) |
| | 0 | 62 | | throw new ClientException(ErrorCodes.InvalidAddress, "Address cannot be empty"); |
| | | 63 | | |
| | | 64 | | // Check if either a PeerAddressInfo or a CompactPubKey was provided |
| | 0 | 65 | | var isPeerAddressInfo = request.NodeInfo.Contains('@') && request.NodeInfo.Contains(':'); |
| | | 66 | | CompactPubKey peerId; |
| | | 67 | | |
| | 0 | 68 | | peerId = isPeerAddressInfo |
| | 0 | 69 | | ? new PeerAddress(request.NodeInfo).PubKey |
| | 0 | 70 | | : new CompactPubKey(Convert.FromHexString(request.NodeInfo)); // Parse as a hex public key |
| | | 71 | | |
| | | 72 | | // Check if we're connected to the peer |
| | 0 | 73 | | var peer = _peerManager.GetPeer(peerId) |
| | 0 | 74 | | ?? await _peerManager.ConnectToPeerAsync(new PeerAddressInfo(request.NodeInfo)); |
| | | 75 | | |
| | | 76 | | // Let's check if we have enough funds to open this channel |
| | 0 | 77 | | var currentHeight = _blockchainMonitor.LastProcessedBlockHeight; |
| | 0 | 78 | | if (_utxoMemoryRepository.GetConfirmedBalance(currentHeight) < request.FundingAmount) |
| | 0 | 79 | | throw new ClientException(ErrorCodes.NotEnoughBalance, "We don't have enough balance to open this channel"); |
| | | 80 | | |
| | | 81 | | // Since we're connected, let's open the channel |
| | 0 | 82 | | var channel = |
| | 0 | 83 | | await _channelFactory.CreateChannelV1AsInitiatorAsync(request, peer.NegotiatedFeatures, peerId); |
| | | 84 | | |
| | | 85 | | // Save the channelId for later |
| | 0 | 86 | | _channelId = channel.ChannelId; |
| | | 87 | | |
| | 0 | 88 | | if (_logger.IsEnabled(LogLevel.Trace)) |
| | 0 | 89 | | _logger.LogTrace("Created Temporary Channel {id} with fundingPubKey: {fundingPubKey}", channel.ChannelId, |
| | 0 | 90 | | channel.LocalKeySet.FundingCompactPubKey); |
| | | 91 | | |
| | | 92 | | // Select UTXOs and mark them as toSpend for this channel |
| | 0 | 93 | | _utxoMemoryRepository.LockUtxosToSpendOnChannel(request.FundingAmount, channel.ChannelId); |
| | | 94 | | |
| | | 95 | | // Create a task completion source for the response |
| | 0 | 96 | | var tsc = new TaskCompletionSource<OpenChannelClientResponse>( |
| | 0 | 97 | | TaskCreationOptions.RunContinuationsAsynchronously); |
| | | 98 | | |
| | | 99 | | try |
| | | 100 | | { |
| | | 101 | | // Add the channel to dictionaries |
| | 0 | 102 | | _channelMemoryRepository.AddTemporaryChannel(peerId, channel); |
| | | 103 | | |
| | | 104 | | // Create the channel type Tlv |
| | 0 | 105 | | var channelTypeFeatureSet = FeatureSet.NewBasicChannelType(); |
| | 0 | 106 | | if (peer.NegotiatedFeatures.OptionAnchors >= FeatureSupport.Optional) |
| | 0 | 107 | | channelTypeFeatureSet.SetFeature(Feature.OptionAnchors, true); |
| | | 108 | | |
| | 0 | 109 | | if (channel.ChannelConfig.UseScidAlias >= FeatureSupport.Optional) |
| | 0 | 110 | | channelTypeFeatureSet.SetFeature(Feature.OptionScidAlias, true); |
| | | 111 | | |
| | 0 | 112 | | if (channel.ChannelConfig.MinimumDepth == 0) |
| | 0 | 113 | | channelTypeFeatureSet.SetFeature(Feature.OptionZeroconf, true); |
| | | 114 | | |
| | 0 | 115 | | var featureSetBytes = channelTypeFeatureSet.GetBytes() ?? throw new ClientException( |
| | 0 | 116 | | ErrorCodes.InvalidOperation, |
| | 0 | 117 | | $"Error creating {nameof(ChannelTypeTlv)}. This should never happen."); |
| | 0 | 118 | | var channelTypeTlv = new ChannelTypeTlv(featureSetBytes); |
| | | 119 | | |
| | | 120 | | // Create UpfrontShutdownScriptTlv if needed |
| | 0 | 121 | | var upfrontShutdownScriptTlv = channel.LocalUpfrontShutdownScript is not null |
| | 0 | 122 | | ? new UpfrontShutdownScriptTlv(channel.LocalUpfrontShutdownScript.Value) |
| | 0 | 123 | | : new UpfrontShutdownScriptTlv(Array.Empty<byte>()); |
| | | 124 | | |
| | | 125 | | // Create the ChannelFlags |
| | 0 | 126 | | var channelFlags = new ChannelFlags(ChannelFlag.None); |
| | 0 | 127 | | if (peer.NegotiatedFeatures.ScidAlias == FeatureSupport.Compulsory) |
| | 0 | 128 | | channelFlags = new ChannelFlags(ChannelFlag.AnnounceChannel); |
| | | 129 | | |
| | | 130 | | // Create the openChannel message |
| | 0 | 131 | | var openChannel1Message = _messageFactory.CreateOpenChannel1Message( |
| | 0 | 132 | | channel.ChannelId, channel.LocalBalance, channel.LocalKeySet.FundingCompactPubKey, |
| | 0 | 133 | | channel.RemoteBalance, channel.ChannelConfig.ChannelReserveAmount, |
| | 0 | 134 | | channel.ChannelConfig.FeeRateAmountPerKw, |
| | 0 | 135 | | channel.ChannelConfig.MaxAcceptedHtlcs, channel.LocalKeySet.RevocationCompactBasepoint, |
| | 0 | 136 | | channel.LocalKeySet.PaymentCompactBasepoint, channel.LocalKeySet.DelayedPaymentCompactBasepoint, |
| | 0 | 137 | | channel.LocalKeySet.HtlcCompactBasepoint, channel.LocalKeySet.CurrentPerCommitmentCompactPoint, |
| | 0 | 138 | | channelFlags, channelTypeTlv, upfrontShutdownScriptTlv); |
| | | 139 | | |
| | 0 | 140 | | if (!peer.TryGetPeerService(out _peerService)) |
| | 0 | 141 | | throw new ClientException(ErrorCodes.InvalidOperation, "Error getting peerService from peer"); |
| | | 142 | | |
| | | 143 | | // Subscribe to the events before sending the message |
| | 0 | 144 | | _peerService.OnAttentionMessageReceived += AttentionMessageHandlerEnvelope; |
| | 0 | 145 | | _peerService.OnDisconnect += PeerDisconnectionEnvelope; |
| | 0 | 146 | | _peerService.OnExceptionRaised += ExceptionRaisedEnvelope; |
| | 0 | 147 | | _channelMemoryRepository.OnChannelUpgraded += ChannelUpgradedHandlerEnvelope; |
| | | 148 | | |
| | 0 | 149 | | if (_logger.IsEnabled(LogLevel.Information)) |
| | 0 | 150 | | _logger.LogInformation("Sending OpenChannel message to peer {peerId} for channel {channelId}", |
| | 0 | 151 | | peerId, |
| | 0 | 152 | | channel.ChannelId); |
| | 0 | 153 | | await _peerService.SendMessageAsync(openChannel1Message); |
| | | 154 | | |
| | 0 | 155 | | return await tsc.Task; |
| | | 156 | | } |
| | 0 | 157 | | catch |
| | | 158 | | { |
| | 0 | 159 | | _utxoMemoryRepository.ReturnUtxosNotSpentOnChannel(_channelId); |
| | | 160 | | |
| | 0 | 161 | | throw; |
| | | 162 | | } |
| | | 163 | | finally |
| | | 164 | | { |
| | | 165 | | //Unsubscribe from the events so we don't have dangling memory |
| | 0 | 166 | | _peerService?.OnAttentionMessageReceived -= AttentionMessageHandlerEnvelope; |
| | 0 | 167 | | _peerService?.OnDisconnect -= PeerDisconnectionEnvelope; |
| | 0 | 168 | | _peerService?.OnExceptionRaised -= ExceptionRaisedEnvelope; |
| | 0 | 169 | | _channelMemoryRepository.OnChannelUpgraded -= ChannelUpgradedHandlerEnvelope; |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | // Envelopes for the events |
| | | 173 | | void AttentionMessageHandlerEnvelope(object? _, AttentionMessageEventArgs args) => |
| | 0 | 174 | | HandleAttentionMessage(args, tsc); |
| | | 175 | | |
| | | 176 | | void PeerDisconnectionEnvelope(object? _, PeerDisconnectedEventArgs args) => |
| | 0 | 177 | | HandlePeerDisconnection(args, channel.RemoteNodeId, tsc); |
| | | 178 | | |
| | | 179 | | void ExceptionRaisedEnvelope(object? _, Exception e) => |
| | 0 | 180 | | HandleExceptionRaised(e, tsc); |
| | | 181 | | |
| | | 182 | | void ChannelUpgradedHandlerEnvelope(object? _, ChannelUpgradedEventArgs args) => |
| | 0 | 183 | | HandleChannelUpgraded(args, tsc); |
| | 0 | 184 | | } |
| | | 185 | | |
| | | 186 | | private void HandleChannelUpgraded(ChannelUpgradedEventArgs args, |
| | | 187 | | TaskCompletionSource<OpenChannelClientResponse> tsc) |
| | | 188 | | { |
| | 0 | 189 | | if (args.OldChannelId != _channelId) |
| | 0 | 190 | | return; |
| | | 191 | | |
| | 0 | 192 | | tsc.TrySetResult(new OpenChannelClientResponse(args.NewChannelId)); |
| | | 193 | | |
| | 0 | 194 | | if (_logger.IsEnabled(LogLevel.Information)) |
| | 0 | 195 | | _logger.LogInformation("Channel {oldChannelId} has been upgraded to {channelId}", args.OldChannelId, |
| | 0 | 196 | | args.NewChannelId); |
| | 0 | 197 | | } |
| | | 198 | | |
| | | 199 | | private void HandleAttentionMessage(AttentionMessageEventArgs args, |
| | | 200 | | TaskCompletionSource<OpenChannelClientResponse> tsc) |
| | | 201 | | { |
| | 0 | 202 | | if (args.ChannelId != _channelId) |
| | 0 | 203 | | return; |
| | | 204 | | |
| | 0 | 205 | | _logger.LogError( |
| | 0 | 206 | | "Received attention message from peer {peerId} for channel {channelId}: {message}", |
| | 0 | 207 | | args.PeerPubKey, args.ChannelId, args.Message); |
| | | 208 | | |
| | 0 | 209 | | tsc.TrySetException(new ChannelErrorException($"Error opening channel: {args.Message}")); |
| | 0 | 210 | | } |
| | | 211 | | |
| | | 212 | | private void HandlePeerDisconnection(PeerDisconnectedEventArgs args, CompactPubKey peerPubKey, |
| | | 213 | | TaskCompletionSource<OpenChannelClientResponse> tsc) |
| | | 214 | | { |
| | 0 | 215 | | if (args.PeerPubKey != peerPubKey) |
| | 0 | 216 | | return; |
| | | 217 | | |
| | 0 | 218 | | _logger.LogError("Peer disconnected without notice"); |
| | 0 | 219 | | tsc.TrySetException(new ConnectionException("Error opening channel: Peer disconnected")); |
| | 0 | 220 | | } |
| | | 221 | | |
| | | 222 | | private void HandleExceptionRaised(Exception e, TaskCompletionSource<OpenChannelClientResponse> tsc) |
| | | 223 | | { |
| | 0 | 224 | | if (e is not ChannelErrorException ce || ce.ChannelId != _channelId) |
| | 0 | 225 | | return; |
| | | 226 | | |
| | 0 | 227 | | _logger.LogError("Exception raised while opening channel: {message}", e.Message); |
| | 0 | 228 | | tsc.TrySetException(e); |
| | 0 | 229 | | } |
| | | 230 | | } |