| | | 1 | | namespace NLightning.Domain.Channels.Factories; |
| | | 2 | | |
| | | 3 | | using Bitcoin.Interfaces; |
| | | 4 | | using Bitcoin.Transactions.Constants; |
| | | 5 | | using Bitcoin.Transactions.Outputs; |
| | | 6 | | using Bitcoin.ValueObjects; |
| | | 7 | | using Client.Requests; |
| | | 8 | | using Constants; |
| | | 9 | | using Crypto.Hashes; |
| | | 10 | | using Crypto.ValueObjects; |
| | | 11 | | using Domain.Enums; |
| | | 12 | | using Enums; |
| | | 13 | | using Exceptions; |
| | | 14 | | using Interfaces; |
| | | 15 | | using Models; |
| | | 16 | | using Money; |
| | | 17 | | using Node.Options; |
| | | 18 | | using Protocol.Interfaces; |
| | | 19 | | using Protocol.Messages; |
| | | 20 | | using Protocol.Models; |
| | | 21 | | using Validators.Parameters; |
| | | 22 | | using ValueObjects; |
| | | 23 | | |
| | | 24 | | public class ChannelFactory : IChannelFactory |
| | | 25 | | { |
| | | 26 | | private readonly IChannelIdFactory _channelIdFactory; |
| | | 27 | | private readonly IChannelOpenValidator _channelOpenValidator; |
| | | 28 | | private readonly IFeeService _feeService; |
| | | 29 | | private readonly ILightningSigner _lightningSigner; |
| | | 30 | | private readonly NodeOptions _nodeOptions; |
| | 0 | 31 | | private readonly ISha256 _sha256; |
| | 0 | 32 | | |
| | 0 | 33 | | public ChannelFactory(IChannelIdFactory channelIdFactory, IChannelOpenValidator channelOpenValidator, |
| | 0 | 34 | | IFeeService feeService, ILightningSigner lightningSigner, NodeOptions nodeOptions, |
| | 0 | 35 | | ISha256 sha256) |
| | 0 | 36 | | { |
| | 0 | 37 | | _channelIdFactory = channelIdFactory; |
| | 0 | 38 | | _channelOpenValidator = channelOpenValidator; |
| | 0 | 39 | | _feeService = feeService; |
| | 0 | 40 | | _lightningSigner = lightningSigner; |
| | 0 | 41 | | _nodeOptions = nodeOptions; |
| | 0 | 42 | | _sha256 = sha256; |
| | 0 | 43 | | } |
| | 0 | 44 | | |
| | | 45 | | public async Task<ChannelModel> CreateChannelV1AsNonInitiatorAsync(OpenChannel1Message message, |
| | | 46 | | FeatureOptions negotiatedFeatures, |
| | 0 | 47 | | CompactPubKey remoteNodeId) |
| | 0 | 48 | | { |
| | 0 | 49 | | var payload = message.Payload; |
| | | 50 | | |
| | 0 | 51 | | // If dual fund is negotiated fail the channel |
| | 0 | 52 | | if (negotiatedFeatures.DualFund == FeatureSupport.Compulsory) |
| | 0 | 53 | | throw new ChannelErrorException("We can only accept dual fund channels"); |
| | | 54 | | |
| | 0 | 55 | | // Perform optional checks for the channel |
| | 0 | 56 | | var ourChannelReserveAmount = GetOurChannelReserveFromFundingAmount(payload.FundingAmount); |
| | 0 | 57 | | _channelOpenValidator.PerformOptionalChecks( |
| | 0 | 58 | | ChannelOpenOptionalValidationParameters.FromOpenChannel1Payload(payload, ourChannelReserveAmount)); |
| | 0 | 59 | | |
| | | 60 | | // Perform mandatory checks for the channel |
| | 0 | 61 | | var currentFee = await _feeService.GetFeeRatePerKwAsync(); |
| | 0 | 62 | | _channelOpenValidator.PerformMandatoryChecks( |
| | 0 | 63 | | ChannelOpenMandatoryValidationParameters.FromOpenChannel1Payload( |
| | 0 | 64 | | message.ChannelTypeTlv, currentFee, negotiatedFeatures, payload), out var minimumDepth); |
| | | 65 | | |
| | 0 | 66 | | // Check for the upfront shutdown script |
| | 0 | 67 | | if (message.UpfrontShutdownScriptTlv is null |
| | 0 | 68 | | && (negotiatedFeatures.UpfrontShutdownScript > FeatureSupport.No || message.ChannelTypeTlv is not null)) |
| | 0 | 69 | | throw new ChannelErrorException("Upfront shutdown script is required but not provided"); |
| | | 70 | | |
| | 0 | 71 | | BitcoinScript? remoteUpfrontShutdownScript = null; |
| | 0 | 72 | | if (message.UpfrontShutdownScriptTlv is not null && message.UpfrontShutdownScriptTlv.Value.Length > 0) |
| | 0 | 73 | | remoteUpfrontShutdownScript = message.UpfrontShutdownScriptTlv.Value; |
| | | 74 | | |
| | 0 | 75 | | // Calculate the amounts |
| | 0 | 76 | | var toLocalAmount = payload.PushAmount; |
| | 0 | 77 | | var toRemoteAmount = payload.FundingAmount - payload.PushAmount; |
| | 0 | 78 | | |
| | 0 | 79 | | // Generate local keys through the signer |
| | 0 | 80 | | var localKeyIndex = _lightningSigner.CreateNewChannel(out var localBasepoints, out var firstPerCommitmentPoint); |
| | 0 | 81 | | |
| | | 82 | | // Create the local key set |
| | 0 | 83 | | var localKeySet = new ChannelKeySetModel(localKeyIndex, localBasepoints.FundingPubKey, |
| | 0 | 84 | | localBasepoints.RevocationBasepoint, localBasepoints.PaymentBasepoint, |
| | 0 | 85 | | localBasepoints.DelayedPaymentBasepoint, localBasepoints.HtlcBasepoint, |
| | 0 | 86 | | firstPerCommitmentPoint); |
| | 0 | 87 | | |
| | 0 | 88 | | // Create the remote key set from the message |
| | 0 | 89 | | var remoteKeySet = ChannelKeySetModel.CreateForRemote(message.Payload.FundingPubKey, |
| | 0 | 90 | | message.Payload.RevocationBasepoint, |
| | 0 | 91 | | message.Payload.PaymentBasepoint, |
| | 0 | 92 | | message.Payload.DelayedPaymentBasepoint, |
| | 0 | 93 | | message.Payload.HtlcBasepoint, |
| | 0 | 94 | | message.Payload.FirstPerCommitmentPoint); |
| | | 95 | | |
| | 0 | 96 | | BitcoinScript? localUpfrontShutdownScript = null; |
| | | 97 | | // Generate our upfront shutdown script |
| | 0 | 98 | | if (_nodeOptions.Features.UpfrontShutdownScript > FeatureSupport.No) |
| | | 99 | | { |
| | | 100 | | // Generate our upfront shutdown script |
| | 0 | 101 | | // TODO: Generate a script from the local key set |
| | 0 | 102 | | // localUpfrontShutdownScript = ; |
| | | 103 | | } |
| | 0 | 104 | | |
| | 0 | 105 | | // Generate the channel configuration |
| | 0 | 106 | | var useScidAlias = FeatureSupport.No; |
| | 0 | 107 | | if (negotiatedFeatures.ScidAlias > FeatureSupport.No) |
| | | 108 | | { |
| | 0 | 109 | | if (message.ChannelTypeTlv?.Features.IsFeatureSet(Feature.OptionScidAlias, true) ?? false) |
| | 0 | 110 | | useScidAlias = FeatureSupport.Compulsory; |
| | 0 | 111 | | else |
| | 0 | 112 | | useScidAlias = FeatureSupport.Optional; |
| | 0 | 113 | | } |
| | 0 | 114 | | |
| | 0 | 115 | | var channelConfig = new ChannelConfig(payload.ChannelReserveAmount, payload.FeeRatePerKw, |
| | 0 | 116 | | payload.HtlcMinimumAmount, _nodeOptions.DustLimitAmount, |
| | 0 | 117 | | payload.MaxAcceptedHtlcs, payload.MaxHtlcValueInFlight, minimumDepth, |
| | 0 | 118 | | negotiatedFeatures.OptionAnchors != FeatureSupport.No, |
| | 0 | 119 | | payload.DustLimitAmount, payload.ToSelfDelay, useScidAlias, |
| | 0 | 120 | | localUpfrontShutdownScript, remoteUpfrontShutdownScript); |
| | | 121 | | |
| | | 122 | | // Generate the commitment number |
| | 0 | 123 | | var commitmentNumber = new CommitmentNumber(remoteKeySet.PaymentCompactBasepoint, |
| | 0 | 124 | | localKeySet.PaymentCompactBasepoint, _sha256); |
| | | 125 | | |
| | | 126 | | try |
| | 0 | 127 | | { |
| | 0 | 128 | | var fundingOutput = new FundingOutputInfo(payload.FundingAmount, localKeySet.FundingCompactPubKey, |
| | 0 | 129 | | remoteKeySet.FundingCompactPubKey); |
| | | 130 | | |
| | 0 | 131 | | // Create the channel |
| | 0 | 132 | | return new ChannelModel(channelConfig, payload.ChannelId, commitmentNumber, fundingOutput, false, null, |
| | 0 | 133 | | null, toLocalAmount, localKeySet, 1, 0, toRemoteAmount, remoteKeySet, 1, |
| | 0 | 134 | | remoteNodeId, 0, ChannelState.V1Opening, ChannelVersion.V1); |
| | 0 | 135 | | } |
| | 0 | 136 | | catch (Exception e) |
| | | 137 | | { |
| | 0 | 138 | | throw new ChannelErrorException("Error creating commitment transaction", e); |
| | | 139 | | } |
| | 0 | 140 | | } |
| | | 141 | | |
| | | 142 | | public async Task<ChannelModel> CreateChannelV1AsInitiatorAsync(OpenChannelClientRequest request, |
| | | 143 | | FeatureOptions negotiatedFeatures, |
| | | 144 | | CompactPubKey remoteNodeId) |
| | | 145 | | { |
| | | 146 | | // If dual fund is negotiated fail the channel |
| | 0 | 147 | | if (negotiatedFeatures.DualFund == FeatureSupport.Compulsory) |
| | 0 | 148 | | throw new ChannelErrorException("We can only open dual fund channels to this peer"); |
| | | 149 | | |
| | | 150 | | // Check if the FundingAmount is too small |
| | 0 | 151 | | if (request.FundingAmount < _nodeOptions.MinimumChannelSize) |
| | 0 | 152 | | throw new ChannelErrorException( |
| | 0 | 153 | | $"Funding amount is smaller than our MinimumChannelSize: {request.FundingAmount} < {_nodeOptions.Minimum |
| | | 154 | | |
| | | 155 | | // Check if our fee is too big |
| | 0 | 156 | | if (request.FeeRatePerKw is not null && request.FeeRatePerKw > ChannelConstants.MaxFeePerKw) |
| | 0 | 157 | | throw new ChannelErrorException($"Fee rate per kw is too large: {request.FeeRatePerKw}"); |
| | 0 | 158 | | |
| | 0 | 159 | | // Check if our fee is too big |
| | 0 | 160 | | if (request.FeeRatePerKw is not null && request.FeeRatePerKw < ChannelConstants.MinFeePerKw) |
| | 0 | 161 | | throw new ChannelErrorException($"Fee rate per kw is too small: {request.FeeRatePerKw}"); |
| | 0 | 162 | | |
| | 0 | 163 | | // Check if the dust limit is greater than the channel reserve amount |
| | 0 | 164 | | var channelReserveAmount = GetOurChannelReserveFromFundingAmount(request.FundingAmount); |
| | 0 | 165 | | if (request.ChannelReserveAmount is not null && request.ChannelReserveAmount > channelReserveAmount) |
| | 0 | 166 | | channelReserveAmount = request.ChannelReserveAmount; |
| | 0 | 167 | | |
| | 0 | 168 | | var dustLimitAmount = ChannelConstants.MinDustLimitAmount; |
| | 0 | 169 | | if (request.DustLimitAmount is not null) |
| | 0 | 170 | | { |
| | | 171 | | // Check if dust_limit_satoshis is too small |
| | 0 | 172 | | if (request.DustLimitAmount < ChannelConstants.MinDustLimitAmount) |
| | 0 | 173 | | throw new ChannelErrorException($"Dust limit amount is too small: {request.DustLimitAmount}"); |
| | 0 | 174 | | |
| | 0 | 175 | | dustLimitAmount = request.DustLimitAmount; |
| | | 176 | | } |
| | 0 | 177 | | |
| | 0 | 178 | | if (dustLimitAmount > channelReserveAmount) |
| | 0 | 179 | | channelReserveAmount = dustLimitAmount; |
| | | 180 | | |
| | 0 | 181 | | // Check if there are enough funds to pay for fees |
| | 0 | 182 | | var currentFeeRatePerKw = request.FeeRatePerKw ?? await _feeService.GetFeeRatePerKwAsync(); |
| | 0 | 183 | | var expectedWeight = negotiatedFeatures.OptionAnchors > FeatureSupport.No |
| | 0 | 184 | | ? TransactionConstants.InitialCommitmentTransactionWeightNoAnchor |
| | 0 | 185 | | : TransactionConstants.InitialCommitmentTransactionWeightWithAnchor; |
| | 0 | 186 | | var expectedFee = LightningMoney.Satoshis(expectedWeight * currentFeeRatePerKw.Satoshi / 1000); |
| | 0 | 187 | | if (request.FundingAmount < expectedFee + channelReserveAmount) |
| | 0 | 188 | | throw new ChannelErrorException($"Funding amount is too small to cover fees: {request.FundingAmount}"); |
| | | 189 | | |
| | | 190 | | // Check if this is a large channel and if we support it |
| | 0 | 191 | | if (request.FundingAmount >= ChannelConstants.LargeChannelAmount && |
| | 0 | 192 | | negotiatedFeatures.LargeChannels == FeatureSupport.No) |
| | 0 | 193 | | throw new ChannelErrorException("The peer doesn't support large channels"); |
| | | 194 | | |
| | | 195 | | // Check if we want zeroconf and if it's negotiated |
| | 0 | 196 | | var minimumDepth = _nodeOptions.MinimumDepth; |
| | 0 | 197 | | if (request.IsZeroConfChannel) |
| | | 198 | | { |
| | 0 | 199 | | if (_nodeOptions.Features.ZeroConf == FeatureSupport.No) |
| | 0 | 200 | | throw new ChannelErrorException( |
| | 0 | 201 | | "ZeroConf feature not supported, change our configuration and try again"); |
| | | 202 | | |
| | 0 | 203 | | if (negotiatedFeatures.ZeroConf == FeatureSupport.No) |
| | 0 | 204 | | throw new ChannelErrorException("ZeroConf not supported by our peer"); |
| | | 205 | | |
| | 0 | 206 | | minimumDepth = 0U; |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | // Calculate the amounts |
| | 0 | 210 | | var toRemoteAmount = request.PushAmount ?? LightningMoney.Zero; |
| | 0 | 211 | | var toLocalAmount = request.FundingAmount - toRemoteAmount; |
| | | 212 | | |
| | | 213 | | // Generate our MaxHtlcValueInFlight if not provided |
| | 0 | 214 | | var maxHtlcValueInFlight = request.MaxHtlcValueInFlight |
| | 0 | 215 | | ?? LightningMoney.Satoshis(_nodeOptions.AllowUpToPercentageOfChannelFundsInFlight * |
| | 0 | 216 | | request.FundingAmount.Satoshi / 100M); |
| | | 217 | | |
| | 0 | 218 | | // Generate local keys through the signer |
| | 0 | 219 | | var localKeyIndex = _lightningSigner.CreateNewChannel(out var localBasepoints, out var firstPerCommitmentPoint); |
| | | 220 | | |
| | | 221 | | // Create the local key set |
| | 0 | 222 | | var localKeySet = new ChannelKeySetModel(localKeyIndex, localBasepoints.FundingPubKey, |
| | 0 | 223 | | localBasepoints.RevocationBasepoint, localBasepoints.PaymentBasepoint, |
| | 0 | 224 | | localBasepoints.DelayedPaymentBasepoint, localBasepoints.HtlcBasepoint, |
| | 0 | 225 | | firstPerCommitmentPoint); |
| | 0 | 226 | | |
| | 0 | 227 | | BitcoinScript? localUpfrontShutdownScript = null; |
| | | 228 | | // Generate our upfront shutdown script |
| | 0 | 229 | | if (negotiatedFeatures.UpfrontShutdownScript == FeatureSupport.Compulsory) |
| | 0 | 230 | | throw new ChannelErrorException("Upfront shutdown script is compulsory but we are not able to send it"); |
| | 0 | 231 | | |
| | 0 | 232 | | if (_nodeOptions.Features.UpfrontShutdownScript > FeatureSupport.No) |
| | | 233 | | { |
| | 0 | 234 | | // Generate our upfront shutdown script |
| | 0 | 235 | | // TODO: Generate a script from the local key set |
| | 0 | 236 | | // localUpfrontShutdownScript = ; |
| | | 237 | | } |
| | | 238 | | |
| | 0 | 239 | | // Generate the channel configuration |
| | 0 | 240 | | var channelConfig = new ChannelConfig(channelReserveAmount, request.FeeRatePerKw ?? currentFeeRatePerKw, |
| | 0 | 241 | | request.HtlcMinimumAmount ?? _nodeOptions.HtlcMinimumAmount, |
| | 0 | 242 | | dustLimitAmount, |
| | 0 | 243 | | request.MaxAcceptedHtlcs ?? _nodeOptions.MaxAcceptedHtlcs, |
| | 0 | 244 | | maxHtlcValueInFlight, minimumDepth, |
| | 0 | 245 | | negotiatedFeatures.OptionAnchors != FeatureSupport.No, |
| | 0 | 246 | | LightningMoney.Zero, request.ToSelfDelay ?? _nodeOptions.ToSelfDelay, |
| | 0 | 247 | | negotiatedFeatures.ScidAlias, localUpfrontShutdownScript); |
| | 0 | 248 | | |
| | 0 | 249 | | try |
| | 0 | 250 | | { |
| | 0 | 251 | | // Create the channel using only our data |
| | 0 | 252 | | return new ChannelModel(channelConfig, _channelIdFactory.CreateTemporaryChannelId(), null, |
| | 0 | 253 | | null, true, null, null, toLocalAmount, localKeySet, 1, 0, toRemoteAmount, |
| | 0 | 254 | | null, 1, remoteNodeId, 0, ChannelState.V1Opening, ChannelVersion.V1); |
| | | 255 | | } |
| | 0 | 256 | | catch (Exception e) |
| | 0 | 257 | | { |
| | 0 | 258 | | throw new ChannelErrorException("Error creating commitment transaction", e); |
| | | 259 | | } |
| | 0 | 260 | | } |
| | 0 | 261 | | |
| | 0 | 262 | | private LightningMoney GetOurChannelReserveFromFundingAmount(LightningMoney fundingAmount) |
| | | 263 | | { |
| | 0 | 264 | | return fundingAmount * 0.01M; |
| | 0 | 265 | | } |
| | | 266 | | } |