| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using NLightning.Domain.Persistence.Interfaces; |
| | | 3 | | |
| | | 4 | | namespace NLightning.Application.Channels.Handlers; |
| | | 5 | | |
| | | 6 | | using Domain.Bitcoin.Enums; |
| | | 7 | | using Domain.Bitcoin.Interfaces; |
| | | 8 | | using Domain.Bitcoin.Transactions.Enums; |
| | | 9 | | using Domain.Bitcoin.Transactions.Interfaces; |
| | | 10 | | using Domain.Bitcoin.Transactions.Outputs; |
| | | 11 | | using Domain.Bitcoin.ValueObjects; |
| | | 12 | | using Domain.Channels.Enums; |
| | | 13 | | using Domain.Channels.Interfaces; |
| | | 14 | | using Domain.Channels.Models; |
| | | 15 | | using Domain.Channels.Validators.Parameters; |
| | | 16 | | using Domain.Channels.ValueObjects; |
| | | 17 | | using Domain.Crypto.Hashes; |
| | | 18 | | using Domain.Crypto.ValueObjects; |
| | | 19 | | using Domain.Enums; |
| | | 20 | | using Domain.Exceptions; |
| | | 21 | | using Domain.Node.Options; |
| | | 22 | | using Domain.Protocol.Interfaces; |
| | | 23 | | using Domain.Protocol.Messages; |
| | | 24 | | using Domain.Protocol.Models; |
| | | 25 | | using Infrastructure.Bitcoin.Builders.Interfaces; |
| | | 26 | | using Infrastructure.Bitcoin.Wallet.Interfaces; |
| | | 27 | | using Interfaces; |
| | | 28 | | |
| | | 29 | | public class AcceptChannel1MessageHandler : IChannelMessageHandler<AcceptChannel1Message> |
| | | 30 | | { |
| | | 31 | | private readonly IBitcoinWalletService _bitcoinWalletService; |
| | | 32 | | private readonly IChannelIdFactory _channelIdFactory; |
| | | 33 | | private readonly IChannelMemoryRepository _channelMemoryRepository; |
| | | 34 | | private readonly IChannelOpenValidator _channelOpenValidator; |
| | | 35 | | private readonly ICommitmentTransactionBuilder _commitmentTransactionBuilder; |
| | | 36 | | private readonly ICommitmentTransactionModelFactory _commitmentTransactionModelFactory; |
| | | 37 | | private readonly IFundingTransactionBuilder _fundingTransactionBuilder; |
| | | 38 | | private readonly IFundingTransactionModelFactory _fundingTransactionModelFactory; |
| | | 39 | | private readonly ILightningSigner _lightningSigner; |
| | | 40 | | private readonly ILogger<OpenChannel1MessageHandler> _logger; |
| | | 41 | | private readonly IMessageFactory _messageFactory; |
| | | 42 | | private readonly ISha256 _sha256; |
| | | 43 | | private readonly IUnitOfWork _unitOfWork; |
| | | 44 | | private readonly IUtxoMemoryRepository _utxoMemoryRepository; |
| | | 45 | | |
| | 0 | 46 | | public AcceptChannel1MessageHandler(IBitcoinWalletService bitcoinWalletService, IChannelIdFactory channelIdFactory, |
| | 0 | 47 | | IChannelMemoryRepository channelMemoryRepository, |
| | 0 | 48 | | IChannelOpenValidator channelOpenValidator, |
| | 0 | 49 | | ICommitmentTransactionBuilder commitmentTransactionBuilder, |
| | 0 | 50 | | ICommitmentTransactionModelFactory commitmentTransactionModelFactory, |
| | 0 | 51 | | IFundingTransactionBuilder fundingTransactionBuilder, |
| | 0 | 52 | | IFundingTransactionModelFactory fundingTransactionModelFactory, |
| | 0 | 53 | | ILightningSigner lightningSigner, ILogger<OpenChannel1MessageHandler> logger, |
| | 0 | 54 | | IMessageFactory messageFactory, ISha256 sha256, IUnitOfWork unitOfWork, |
| | 0 | 55 | | IUtxoMemoryRepository utxoMemoryRepository) |
| | | 56 | | { |
| | 0 | 57 | | _bitcoinWalletService = bitcoinWalletService; |
| | 0 | 58 | | _channelIdFactory = channelIdFactory; |
| | 0 | 59 | | _channelMemoryRepository = channelMemoryRepository; |
| | 0 | 60 | | _channelOpenValidator = channelOpenValidator; |
| | 0 | 61 | | _commitmentTransactionBuilder = commitmentTransactionBuilder; |
| | 0 | 62 | | _commitmentTransactionModelFactory = commitmentTransactionModelFactory; |
| | 0 | 63 | | _fundingTransactionBuilder = fundingTransactionBuilder; |
| | 0 | 64 | | _fundingTransactionModelFactory = fundingTransactionModelFactory; |
| | 0 | 65 | | _lightningSigner = lightningSigner; |
| | 0 | 66 | | _logger = logger; |
| | 0 | 67 | | _messageFactory = messageFactory; |
| | 0 | 68 | | _sha256 = sha256; |
| | 0 | 69 | | _unitOfWork = unitOfWork; |
| | 0 | 70 | | _utxoMemoryRepository = utxoMemoryRepository; |
| | 0 | 71 | | } |
| | | 72 | | |
| | | 73 | | public async Task<IChannelMessage?> HandleAsync(AcceptChannel1Message message, ChannelState currentState, |
| | | 74 | | FeatureOptions negotiatedFeatures, CompactPubKey peerPubKey) |
| | | 75 | | { |
| | 0 | 76 | | if (_logger.IsEnabled(LogLevel.Trace)) |
| | 0 | 77 | | _logger.LogTrace("Processing AcceptChannel1Message with ChannelId: {ChannelId} from Peer: {PeerPubKey}", |
| | 0 | 78 | | message.Payload.ChannelId, peerPubKey); |
| | | 79 | | |
| | 0 | 80 | | var payload = message.Payload; |
| | | 81 | | |
| | 0 | 82 | | if (currentState != ChannelState.None) |
| | 0 | 83 | | throw new ChannelErrorException("A channel with this id already exists", payload.ChannelId); |
| | | 84 | | |
| | | 85 | | // Check if there's a temporary channel for this peer |
| | 0 | 86 | | if (_channelMemoryRepository.TryGetTemporaryChannelState(peerPubKey, payload.ChannelId, out currentState)) |
| | | 87 | | { |
| | 0 | 88 | | if (currentState != ChannelState.V1Opening) |
| | | 89 | | { |
| | 0 | 90 | | throw new ChannelErrorException("Channel had the wrong state", payload.ChannelId, |
| | 0 | 91 | | "This channel is already being negotiated with peer"); |
| | | 92 | | } |
| | | 93 | | } |
| | | 94 | | |
| | | 95 | | // Get the temporary channel |
| | 0 | 96 | | if (!_channelMemoryRepository.TryGetTemporaryChannel(peerPubKey, payload.ChannelId, out var tempChannel)) |
| | 0 | 97 | | throw new ChannelErrorException("Temporary channel not found", payload.ChannelId); |
| | | 98 | | |
| | | 99 | | // Check if the channel type was negotiated and the channel type is present |
| | 0 | 100 | | if (message.ChannelTypeTlv is null) |
| | 0 | 101 | | throw new ChannelErrorException("Channel type was not provided"); |
| | | 102 | | |
| | | 103 | | // Perform optional checks for the channel |
| | 0 | 104 | | _channelOpenValidator.PerformOptionalChecks( |
| | 0 | 105 | | ChannelOpenOptionalValidationParameters.FromAcceptChannel1Payload( |
| | 0 | 106 | | payload, tempChannel.ChannelConfig.ChannelReserveAmount)); |
| | | 107 | | |
| | | 108 | | // Perform mandatory checks for the channel |
| | 0 | 109 | | _channelOpenValidator.PerformMandatoryChecks(ChannelOpenMandatoryValidationParameters.FromAcceptChannel1Payload( |
| | 0 | 110 | | message.ChannelTypeTlv, |
| | 0 | 111 | | tempChannel.ChannelConfig.FeeRateAmountPerKw, |
| | 0 | 112 | | negotiatedFeatures, payload), out var minimumDepth); |
| | | 113 | | |
| | 0 | 114 | | if (minimumDepth != tempChannel.ChannelConfig.MinimumDepth) |
| | 0 | 115 | | throw new ChannelErrorException("Minimum depth is not acceptable", payload.ChannelId); |
| | | 116 | | |
| | | 117 | | // Check for the upfront shutdown script |
| | 0 | 118 | | if (message.UpfrontShutdownScriptTlv is null |
| | 0 | 119 | | && (negotiatedFeatures.UpfrontShutdownScript > FeatureSupport.No || message.ChannelTypeTlv is not null)) |
| | 0 | 120 | | throw new ChannelErrorException("Upfront shutdown script is required but not provided"); |
| | | 121 | | |
| | 0 | 122 | | BitcoinScript? remoteUpfrontShutdownScript = null; |
| | 0 | 123 | | if (message.UpfrontShutdownScriptTlv is not null && message.UpfrontShutdownScriptTlv.Value.Length > 0) |
| | 0 | 124 | | remoteUpfrontShutdownScript = message.UpfrontShutdownScriptTlv.Value; |
| | | 125 | | |
| | | 126 | | // Create the remote key set from the message |
| | 0 | 127 | | var remoteKeySet = ChannelKeySetModel.CreateForRemote(message.Payload.FundingPubKey, |
| | 0 | 128 | | message.Payload.RevocationBasepoint, |
| | 0 | 129 | | message.Payload.PaymentBasepoint, |
| | 0 | 130 | | message.Payload.DelayedPaymentBasepoint, |
| | 0 | 131 | | message.Payload.HtlcBasepoint, |
| | 0 | 132 | | message.Payload.FirstPerCommitmentPoint); |
| | | 133 | | |
| | 0 | 134 | | tempChannel.AddRemoteKeySet(remoteKeySet); |
| | | 135 | | |
| | | 136 | | // Create a new ChannelConfig with the remote-provided values |
| | 0 | 137 | | var channelConfig = new ChannelConfig(tempChannel.ChannelConfig.ChannelReserveAmount, |
| | 0 | 138 | | tempChannel.ChannelConfig.FeeRateAmountPerKw, |
| | 0 | 139 | | tempChannel.ChannelConfig.HtlcMinimumAmount, |
| | 0 | 140 | | tempChannel.ChannelConfig.LocalDustLimitAmount, |
| | 0 | 141 | | tempChannel.ChannelConfig.MaxAcceptedHtlcs, |
| | 0 | 142 | | tempChannel.ChannelConfig.MaxHtlcAmountInFlight, |
| | 0 | 143 | | tempChannel.ChannelConfig.MinimumDepth, |
| | 0 | 144 | | tempChannel.ChannelConfig.OptionAnchorOutputs, |
| | 0 | 145 | | payload.DustLimitAmount, payload.ToSelfDelay, |
| | 0 | 146 | | tempChannel.ChannelConfig.UseScidAlias, |
| | 0 | 147 | | tempChannel.ChannelConfig.LocalUpfrontShutdownScript, |
| | 0 | 148 | | remoteUpfrontShutdownScript); |
| | | 149 | | |
| | 0 | 150 | | tempChannel.UpdateChannelConfig(channelConfig); |
| | | 151 | | |
| | | 152 | | // Generate the correct commitment number |
| | 0 | 153 | | var commitmentNumber = new CommitmentNumber(tempChannel.LocalKeySet.PaymentCompactBasepoint, |
| | 0 | 154 | | remoteKeySet.PaymentCompactBasepoint, _sha256); |
| | | 155 | | |
| | 0 | 156 | | tempChannel.AddCommitmentNumber(commitmentNumber); |
| | | 157 | | |
| | | 158 | | // Keep the oldChannelId for later |
| | 0 | 159 | | var oldChannelId = tempChannel.ChannelId; |
| | | 160 | | |
| | | 161 | | try |
| | | 162 | | { |
| | 0 | 163 | | var fundingAmount = tempChannel.LocalBalance + tempChannel.RemoteBalance; |
| | 0 | 164 | | var fundingOutput = new FundingOutputInfo(fundingAmount, tempChannel.LocalKeySet.FundingCompactPubKey, |
| | 0 | 165 | | remoteKeySet.FundingCompactPubKey); |
| | | 166 | | |
| | 0 | 167 | | tempChannel.AddFundingOutput(fundingOutput); |
| | | 168 | | |
| | | 169 | | // Get the utxos to create the funding transaction |
| | 0 | 170 | | var utxos = _utxoMemoryRepository.GetLockedUtxosForChannel(tempChannel.ChannelId); |
| | | 171 | | |
| | | 172 | | // Get a change address in case we need one |
| | 0 | 173 | | var walletAddress = await _bitcoinWalletService.GetUnusedAddressAsync(AddressType.P2Wpkh, true); |
| | | 174 | | |
| | | 175 | | // Create the funding transaction |
| | 0 | 176 | | var fundingTransactionModel = _fundingTransactionModelFactory.Create(tempChannel, utxos, walletAddress); |
| | 0 | 177 | | _ = _fundingTransactionBuilder.Build(fundingTransactionModel); |
| | 0 | 178 | | if (fundingOutput.TransactionId is null || fundingOutput.Index is null) |
| | 0 | 179 | | throw new ChannelErrorException("Error building the funding transaction"); |
| | | 180 | | |
| | | 181 | | // If a change was needed, save the change data to the channel |
| | 0 | 182 | | if (fundingTransactionModel.ChangeAddress is not null) |
| | 0 | 183 | | tempChannel.ChangeAddress = fundingTransactionModel.ChangeAddress; |
| | | 184 | | |
| | | 185 | | // Create a new channelId |
| | 0 | 186 | | tempChannel.UpdateChannelId( |
| | 0 | 187 | | _channelIdFactory.CreateV1(fundingOutput.TransactionId.Value, fundingOutput.Index.Value)); |
| | | 188 | | |
| | | 189 | | // Check if the channel already exists in the database (it never should) |
| | 0 | 190 | | var existingChannel = await _unitOfWork.ChannelDbRepository.GetByIdAsync(tempChannel.ChannelId); |
| | 0 | 191 | | if (existingChannel is not null) |
| | 0 | 192 | | throw new ChannelErrorException("Channel already exists in the database", tempChannel.ChannelId, |
| | 0 | 193 | | "Sorry, we had an internal error"); |
| | | 194 | | |
| | | 195 | | // Register the channel with the signer |
| | 0 | 196 | | _lightningSigner.RegisterChannel(tempChannel.ChannelId, tempChannel.GetSigningInfo()); |
| | | 197 | | |
| | | 198 | | // Generate the base commitment transactions |
| | 0 | 199 | | var remoteCommitmentTransaction = |
| | 0 | 200 | | _commitmentTransactionModelFactory.CreateCommitmentTransactionModel(tempChannel, CommitmentSide.Remote); |
| | | 201 | | |
| | | 202 | | // Build the output and the transactions |
| | 0 | 203 | | var remoteUnsignedCommitmentTransaction = _commitmentTransactionBuilder.Build(remoteCommitmentTransaction); |
| | | 204 | | |
| | | 205 | | // Sign their remote commitment transaction |
| | 0 | 206 | | var ourSignature = |
| | 0 | 207 | | _lightningSigner.SignChannelTransaction(tempChannel.ChannelId, remoteUnsignedCommitmentTransaction); |
| | | 208 | | |
| | | 209 | | // Update the channel with the new signature and the new state |
| | 0 | 210 | | tempChannel.UpdateLastSentSignature(ourSignature); |
| | 0 | 211 | | tempChannel.UpdateState(ChannelState.V1FundingCreated); |
| | | 212 | | |
| | | 213 | | // Create the funding created message |
| | 0 | 214 | | var fundingCreatedMessage = |
| | 0 | 215 | | _messageFactory.CreateFundingCreatedMessage(oldChannelId, fundingOutput.TransactionId.Value, |
| | 0 | 216 | | fundingOutput.Index.Value, ourSignature); |
| | | 217 | | |
| | | 218 | | // Upgrade the channel in the dictionary |
| | 0 | 219 | | _channelMemoryRepository.UpgradeChannel(oldChannelId, tempChannel); |
| | | 220 | | |
| | | 221 | | // Update the locked utxos |
| | 0 | 222 | | _utxoMemoryRepository.UpgradeChannelIdOnLockedUtxos(oldChannelId, tempChannel.ChannelId); |
| | | 223 | | |
| | 0 | 224 | | return fundingCreatedMessage; |
| | | 225 | | } |
| | 0 | 226 | | catch (Exception e) |
| | | 227 | | { |
| | 0 | 228 | | if (_logger.IsEnabled(LogLevel.Information)) |
| | 0 | 229 | | _logger.LogInformation("Forgetting channel {channelId}", tempChannel.ChannelId); |
| | | 230 | | |
| | 0 | 231 | | if (tempChannel.ChannelId != oldChannelId) |
| | | 232 | | { |
| | 0 | 233 | | if (!_channelMemoryRepository.TryRemoveTemporaryChannel(tempChannel.RemoteNodeId, |
| | 0 | 234 | | tempChannel.ChannelId)) |
| | 0 | 235 | | _logger.LogWarning("Unable to remove temporary channel with id {channelId} for peer {peerPubKey}", |
| | 0 | 236 | | tempChannel.ChannelId, peerPubKey); |
| | 0 | 237 | | else if (!_channelMemoryRepository.TryRemoveChannel(tempChannel.ChannelId)) |
| | 0 | 238 | | _logger.LogWarning("Unable to remove channel with id {channelId}", tempChannel.ChannelId); |
| | | 239 | | } |
| | | 240 | | |
| | 0 | 241 | | throw new ChannelErrorException("Error creating commitment transaction", e); |
| | | 242 | | } |
| | 0 | 243 | | } |
| | | 244 | | } |