| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using NBitcoin; |
| | | 4 | | using NBitcoin.Crypto; |
| | | 5 | | |
| | | 6 | | namespace NLightning.Infrastructure.Bitcoin.Signers; |
| | | 7 | | |
| | | 8 | | using Builders; |
| | | 9 | | using Domain.Bitcoin.Enums; |
| | | 10 | | using Domain.Bitcoin.Interfaces; |
| | | 11 | | using Domain.Bitcoin.Transactions.Outputs; |
| | | 12 | | using Domain.Bitcoin.ValueObjects; |
| | | 13 | | using Domain.Bitcoin.Wallet.Models; |
| | | 14 | | using Domain.Channels.ValueObjects; |
| | | 15 | | using Domain.Crypto.Constants; |
| | | 16 | | using Domain.Crypto.ValueObjects; |
| | | 17 | | using Domain.Exceptions; |
| | | 18 | | using Domain.Node.Options; |
| | | 19 | | using Domain.Protocol.Interfaces; |
| | | 20 | | |
| | | 21 | | public class LocalLightningSigner : ILightningSigner |
| | | 22 | | { |
| | | 23 | | private const int FundingDerivationIndex = 0; // m/0' is the funding key |
| | | 24 | | private const int RevocationDerivationIndex = 1; // m/1' is the revocation key |
| | | 25 | | private const int PaymentDerivationIndex = 2; // m/2' is the payment key |
| | | 26 | | private const int DelayedPaymentDerivationIndex = 3; // m/3' is the delayed payment key |
| | | 27 | | private const int HtlcDerivationIndex = 4; // m/4' is the HTLC key |
| | | 28 | | private const int PerCommitmentSeedDerivationIndex = 5; // m/5' is the per-commitment seed |
| | | 29 | | |
| | | 30 | | private readonly ISecureKeyManager _secureKeyManager; |
| | 0 | 31 | | private readonly IUtxoMemoryRepository _utxoMemoryRepository; |
| | | 32 | | private readonly IFundingOutputBuilder _fundingOutputBuilder; |
| | | 33 | | private readonly IKeyDerivationService _keyDerivationService; |
| | 72 | 34 | | private readonly ConcurrentDictionary<ChannelId, ChannelSigningInfo> _channelSigningInfo = new(); |
| | 0 | 35 | | private readonly ILogger<LocalLightningSigner> _logger; |
| | 0 | 36 | | private readonly Network _network; |
| | 0 | 37 | | |
| | 72 | 38 | | public LocalLightningSigner(IFundingOutputBuilder fundingOutputBuilder, |
| | 72 | 39 | | IKeyDerivationService keyDerivationService, ILogger<LocalLightningSigner> logger, |
| | 72 | 40 | | NodeOptions nodeOptions, ISecureKeyManager secureKeyManager, |
| | 72 | 41 | | IUtxoMemoryRepository utxoMemoryRepository) |
| | 0 | 42 | | { |
| | 72 | 43 | | _fundingOutputBuilder = fundingOutputBuilder; |
| | 72 | 44 | | _keyDerivationService = keyDerivationService; |
| | 72 | 45 | | _logger = logger; |
| | 72 | 46 | | _secureKeyManager = secureKeyManager; |
| | 72 | 47 | | _utxoMemoryRepository = utxoMemoryRepository; |
| | 0 | 48 | | |
| | 72 | 49 | | _network = Network.GetNetwork(nodeOptions.BitcoinNetwork) ?? |
| | 72 | 50 | | throw new ArgumentException("Invalid Bitcoin network specified", nameof(nodeOptions)); |
| | | 51 | | |
| | | 52 | | // TODO: Load channel key data from database |
| | 72 | 53 | | } |
| | 0 | 54 | | |
| | 0 | 55 | | /// <inheritdoc /> |
| | | 56 | | public uint CreateNewChannel(out ChannelBasepoints basepoints, out CompactPubKey firstPerCommitmentPoint) |
| | | 57 | | { |
| | 0 | 58 | | // Generate a new key for this channel |
| | 0 | 59 | | var channelPrivExtKey = _secureKeyManager.GetNextChannelKey(out var index); |
| | 0 | 60 | | var channelKey = ExtKey.CreateFromBytes(channelPrivExtKey); |
| | 0 | 61 | | |
| | 0 | 62 | | // Generate Lightning basepoints using proper BIP32 derivation paths |
| | 0 | 63 | | using var localFundingSecret = GenerateFundingPrivateKey(channelKey); |
| | 0 | 64 | | using var localRevocationSecret = channelKey.Derive(RevocationDerivationIndex, true).PrivateKey; |
| | 0 | 65 | | using var localPaymentSecret = channelKey.Derive(PaymentDerivationIndex, true).PrivateKey; |
| | 0 | 66 | | using var localDelayedPaymentSecret = channelKey.Derive(DelayedPaymentDerivationIndex, true).PrivateKey; |
| | 0 | 67 | | using var localHtlcSecret = channelKey.Derive(HtlcDerivationIndex, true).PrivateKey; |
| | 0 | 68 | | using var perCommitmentSeed = channelKey.Derive(PerCommitmentSeedDerivationIndex, true).PrivateKey; |
| | 0 | 69 | | |
| | 0 | 70 | | // Generate static basepoints (these don't change per commitment) |
| | 0 | 71 | | basepoints = new ChannelBasepoints( |
| | 0 | 72 | | localFundingSecret.PubKey.ToBytes(), |
| | 0 | 73 | | localRevocationSecret.PubKey.ToBytes(), |
| | 0 | 74 | | localPaymentSecret.PubKey.ToBytes(), |
| | 0 | 75 | | localDelayedPaymentSecret.PubKey.ToBytes(), |
| | 0 | 76 | | localHtlcSecret.PubKey.ToBytes() |
| | 0 | 77 | | ); |
| | 0 | 78 | | |
| | | 79 | | // Generate the first per-commitment point |
| | 0 | 80 | | var firstPerCommitmentSecretBytes = _keyDerivationService |
| | 0 | 81 | | .GeneratePerCommitmentSecret(perCommitmentSeed.ToBytes(), CryptoConstants.FirstPerCommitmentIndex); |
| | 0 | 82 | | using var firstPerCommitmentSecret = new Key(firstPerCommitmentSecretBytes); |
| | 0 | 83 | | firstPerCommitmentPoint = firstPerCommitmentSecret.PubKey.ToBytes(); |
| | | 84 | | |
| | 0 | 85 | | return index; |
| | 0 | 86 | | } |
| | | 87 | | |
| | | 88 | | /// <inheritdoc /> |
| | 0 | 89 | | public ChannelBasepoints GetChannelBasepoints(uint channelKeyIndex) |
| | 0 | 90 | | { |
| | 0 | 91 | | _logger.LogTrace("Generating channel basepoints for key index {ChannelKeyIndex}", channelKeyIndex); |
| | 0 | 92 | | |
| | 0 | 93 | | // Recreate the basepoints from the channel key index |
| | 0 | 94 | | var channelExtKey = _secureKeyManager.GetChannelKeyAtIndex(channelKeyIndex); |
| | 0 | 95 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | 0 | 96 | | |
| | 0 | 97 | | using var localFundingSecret = channelKey.Derive(FundingDerivationIndex, true).PrivateKey; |
| | 0 | 98 | | using var localRevocationSecret = channelKey.Derive(RevocationDerivationIndex, true).PrivateKey; |
| | 0 | 99 | | using var localPaymentSecret = channelKey.Derive(PaymentDerivationIndex, true).PrivateKey; |
| | 0 | 100 | | using var localDelayedPaymentSecret = channelKey.Derive(DelayedPaymentDerivationIndex, true).PrivateKey; |
| | 0 | 101 | | using var localHtlcSecret = channelKey.Derive(HtlcDerivationIndex, true).PrivateKey; |
| | 0 | 102 | | |
| | 0 | 103 | | return new ChannelBasepoints( |
| | 0 | 104 | | localFundingSecret.PubKey.ToBytes(), |
| | 0 | 105 | | localRevocationSecret.PubKey.ToBytes(), |
| | 0 | 106 | | localPaymentSecret.PubKey.ToBytes(), |
| | 0 | 107 | | localDelayedPaymentSecret.PubKey.ToBytes(), |
| | 0 | 108 | | localHtlcSecret.PubKey.ToBytes() |
| | 0 | 109 | | ); |
| | 0 | 110 | | } |
| | | 111 | | |
| | 0 | 112 | | /// <inheritdoc /> |
| | 0 | 113 | | public ChannelBasepoints GetChannelBasepoints(ChannelId channelId) |
| | | 114 | | { |
| | 0 | 115 | | _logger.LogTrace("Retrieving channel basepoints for channel {ChannelId}", channelId); |
| | | 116 | | |
| | 0 | 117 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 118 | | throw new SignerException($"Channel {channelId} not registered", channelId); |
| | 0 | 119 | | |
| | 0 | 120 | | return GetChannelBasepoints(signingInfo.ChannelKeyIndex); |
| | | 121 | | } |
| | | 122 | | |
| | | 123 | | /// <inheritdoc /> |
| | 0 | 124 | | public CompactPubKey GetNodePublicKey() => _secureKeyManager.GetNodeKeyPair().CompactPubKey; |
| | 0 | 125 | | |
| | 0 | 126 | | /// <inheritdoc /> |
| | | 127 | | public CompactPubKey GetPerCommitmentPoint(uint channelKeyIndex, ulong commitmentNumber) |
| | | 128 | | { |
| | 0 | 129 | | _logger.LogTrace( |
| | 0 | 130 | | "Generating per-commitment point for channel key index {ChannelKeyIndex} and commitment number {CommitmentNu |
| | 0 | 131 | | channelKeyIndex, commitmentNumber); |
| | | 132 | | |
| | 0 | 133 | | // Derive the per-commitment seed from the channel key |
| | 0 | 134 | | var channelExtKey = _secureKeyManager.GetChannelKeyAtIndex(channelKeyIndex); |
| | 0 | 135 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | 0 | 136 | | using var perCommitmentSeed = channelKey.Derive(PerCommitmentSeedDerivationIndex, true).PrivateKey; |
| | 0 | 137 | | |
| | 0 | 138 | | var perCommitmentSecret = |
| | 0 | 139 | | _keyDerivationService.GeneratePerCommitmentSecret(perCommitmentSeed.ToBytes(), commitmentNumber); |
| | | 140 | | |
| | 0 | 141 | | var perCommitmentPoint = new Key(perCommitmentSecret).PubKey; |
| | 0 | 142 | | return perCommitmentPoint.ToBytes(); |
| | 0 | 143 | | } |
| | 0 | 144 | | |
| | | 145 | | /// <inheritdoc /> |
| | 0 | 146 | | public CompactPubKey GetPerCommitmentPoint(ChannelId channelId, ulong commitmentNumber) |
| | | 147 | | { |
| | 0 | 148 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 149 | | throw new SignerException($"Channel {channelId} not registered", channelId); |
| | | 150 | | |
| | 0 | 151 | | return GetPerCommitmentPoint(signingInfo.ChannelKeyIndex, commitmentNumber); |
| | 0 | 152 | | } |
| | | 153 | | |
| | 0 | 154 | | /// <inheritdoc /> |
| | 0 | 155 | | public void RegisterChannel(ChannelId channelId, ChannelSigningInfo signingInfo) |
| | | 156 | | { |
| | 68 | 157 | | _logger.LogTrace("Registering channel {ChannelId} with signing info", channelId); |
| | | 158 | | |
| | 68 | 159 | | _channelSigningInfo.TryAdd(channelId, signingInfo); |
| | 68 | 160 | | } |
| | 0 | 161 | | |
| | 0 | 162 | | /// <inheritdoc /> |
| | | 163 | | public Secret ReleasePerCommitmentSecret(uint channelKeyIndex, ulong commitmentNumber) |
| | | 164 | | { |
| | 0 | 165 | | _logger.LogTrace( |
| | 0 | 166 | | "Releasing per-commitment secret for channel key index {ChannelKeyIndex} and commitment number {CommitmentNu |
| | 0 | 167 | | channelKeyIndex, commitmentNumber); |
| | | 168 | | |
| | 0 | 169 | | // Derive the per-commitment seed from the channel key |
| | 0 | 170 | | var channelExtKey = _secureKeyManager.GetChannelKeyAtIndex(channelKeyIndex); |
| | 0 | 171 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | 0 | 172 | | using var perCommitmentSeed = channelKey.Derive(PerCommitmentSeedDerivationIndex, true).PrivateKey; |
| | | 173 | | |
| | 0 | 174 | | return _keyDerivationService.GeneratePerCommitmentSecret( |
| | 0 | 175 | | perCommitmentSeed.ToBytes(), commitmentNumber); |
| | 0 | 176 | | } |
| | 0 | 177 | | |
| | | 178 | | /// <inheritdoc /> |
| | 0 | 179 | | public Secret ReleasePerCommitmentSecret(ChannelId channelId, ulong commitmentNumber) |
| | | 180 | | { |
| | 0 | 181 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 182 | | throw new SignerException($"Channel {channelId} not registered", channelId); |
| | | 183 | | |
| | 0 | 184 | | return ReleasePerCommitmentSecret(signingInfo.ChannelKeyIndex, commitmentNumber); |
| | 0 | 185 | | } |
| | 0 | 186 | | |
| | | 187 | | public bool SignWalletTransaction(SignedTransaction unsignedTransaction) |
| | 0 | 188 | | { |
| | 0 | 189 | | throw new NotImplementedException(); |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | public bool SignFundingTransaction(ChannelId channelId, SignedTransaction unsignedTransaction) |
| | | 193 | | { |
| | 0 | 194 | | _logger.LogTrace("Signing funding transaction for channel {ChannelId} with TxId {TxId}", channelId, |
| | 0 | 195 | | unsignedTransaction.TxId); |
| | 0 | 196 | | |
| | 0 | 197 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 198 | | throw new SignerException($"Channel {channelId} not registered with signer", channelId); |
| | 0 | 199 | | |
| | | 200 | | Transaction nBitcoinTx; |
| | | 201 | | try |
| | | 202 | | { |
| | 0 | 203 | | nBitcoinTx = Transaction.Load(unsignedTransaction.RawTxBytes, _network); |
| | 0 | 204 | | } |
| | 0 | 205 | | catch (Exception ex) |
| | 0 | 206 | | { |
| | 0 | 207 | | throw new ArgumentException( |
| | 0 | 208 | | $"Failed to load transaction from RawTxBytes. TxId hint: {unsignedTransaction.TxId}", ex); |
| | 0 | 209 | | } |
| | 0 | 210 | | |
| | | 211 | | try |
| | | 212 | | { |
| | 0 | 213 | | // Verify the funding output exists and is correct |
| | 0 | 214 | | if (signingInfo.FundingOutputIndex >= nBitcoinTx.Outputs.Count) |
| | 0 | 215 | | throw new SignerException($"Funding output index {signingInfo.FundingOutputIndex} is out of range", |
| | 0 | 216 | | channelId); |
| | | 217 | | |
| | 0 | 218 | | // Build the funding output using the channel's signing info |
| | 0 | 219 | | var fundingOutputInfo = new FundingOutputInfo(signingInfo.FundingSatoshis, signingInfo.LocalFundingPubKey, |
| | 0 | 220 | | signingInfo.RemoteFundingPubKey, signingInfo.FundingTxId, |
| | 0 | 221 | | signingInfo.FundingOutputIndex); |
| | 0 | 222 | | |
| | 0 | 223 | | var expectedFundingOutput = _fundingOutputBuilder.Build(fundingOutputInfo); |
| | 0 | 224 | | var expectedTxOut = expectedFundingOutput.ToTxOut(); |
| | | 225 | | |
| | 0 | 226 | | // Validate the transaction output matches what we expect |
| | 0 | 227 | | var actualTxOut = nBitcoinTx.Outputs[signingInfo.FundingOutputIndex]; |
| | 0 | 228 | | if (!actualTxOut.ToBytes().SequenceEqual(expectedTxOut.ToBytes())) |
| | 0 | 229 | | throw new SignerException("Funding output script does not match expected script", channelId); |
| | | 230 | | |
| | 0 | 231 | | if (actualTxOut.Value != expectedTxOut.Value) |
| | 0 | 232 | | throw new SignerException( |
| | 0 | 233 | | $"Funding output amount {actualTxOut.Value} does not match expected amount {expectedTxOut.Value}", |
| | 0 | 234 | | channelId); |
| | 0 | 235 | | |
| | 0 | 236 | | _logger.LogDebug("Funding output validation passed for channel {ChannelId}", channelId); |
| | | 237 | | |
| | 0 | 238 | | // Check transaction structure |
| | 0 | 239 | | if (nBitcoinTx.Inputs.Count == 0) |
| | 0 | 240 | | throw new SignerException("Funding transaction has no inputs", channelId); |
| | | 241 | | |
| | | 242 | | // Get the utxoSet for the channel |
| | 0 | 243 | | var utxoModels = _utxoMemoryRepository.GetLockedUtxosForChannel(channelId); |
| | 0 | 244 | | |
| | 0 | 245 | | var signedInputCount = 0; |
| | 0 | 246 | | var prevOuts = new TxOut[nBitcoinTx.Inputs.Count]; |
| | 0 | 247 | | var signingKeys = new Key?[nBitcoinTx.Inputs.Count]; |
| | 0 | 248 | | var taprootKeyPairs = new TaprootKeyPair?[nBitcoinTx.Inputs.Count]; |
| | 0 | 249 | | var utxos = new UtxoModel[nBitcoinTx.Inputs.Count]; |
| | | 250 | | |
| | | 251 | | // Sign each input |
| | 0 | 252 | | for (var i = 0; i < nBitcoinTx.Inputs.Count; i++) |
| | | 253 | | { |
| | 0 | 254 | | var input = nBitcoinTx.Inputs[i]; |
| | 0 | 255 | | |
| | 0 | 256 | | // Try to get the address being spent |
| | 0 | 257 | | var utxo = utxoModels.FirstOrDefault(x => x.TxId.Equals(new TxId(input.PrevOut.Hash.ToBytes())) |
| | 0 | 258 | | && x.Index.Equals(input.PrevOut.N)); |
| | 0 | 259 | | if (utxo is null) |
| | | 260 | | { |
| | 0 | 261 | | _logger.LogWarning("Could not find UTXO for input {InputIndex} in funding transaction", i); |
| | 0 | 262 | | continue; |
| | | 263 | | } |
| | 0 | 264 | | |
| | 0 | 265 | | if (utxo.WalletAddress is null) |
| | | 266 | | { |
| | 0 | 267 | | _logger.LogWarning( |
| | 0 | 268 | | "UTXO did not have a WalletAddress for input {InputIndex} in funding transaction", i); |
| | 0 | 269 | | continue; |
| | 0 | 270 | | } |
| | 0 | 271 | | |
| | 0 | 272 | | utxos[i] = utxo; |
| | 0 | 273 | | |
| | 0 | 274 | | try |
| | | 275 | | { |
| | | 276 | | // Create the scriptPubKey and previous output based on the address type |
| | | 277 | | Script scriptPubKey; |
| | | 278 | | ExtPrivKey signingExtKey; |
| | 0 | 279 | | Key? signingKey = null; |
| | 0 | 280 | | TaprootKeyPair? taprootKeyPair = null; |
| | 0 | 281 | | |
| | 0 | 282 | | switch (utxo.AddressType) |
| | 0 | 283 | | { |
| | 0 | 284 | | case AddressType.P2Wpkh: |
| | 0 | 285 | | // Derive the key for this specific UTXO |
| | 0 | 286 | | signingExtKey = |
| | 0 | 287 | | _secureKeyManager.GetDepositP2WpkhKeyAtIndex( |
| | 0 | 288 | | utxo.WalletAddress.Index, utxo.WalletAddress.IsChange); |
| | 0 | 289 | | signingKey = ExtKey.CreateFromBytes(signingExtKey).PrivateKey; |
| | 0 | 290 | | // For P2WPKH: OP_0 <20-byte-pubkey-hash> |
| | 0 | 291 | | scriptPubKey = signingKey.PubKey.WitHash.ScriptPubKey; |
| | 0 | 292 | | break; |
| | | 293 | | |
| | 0 | 294 | | case AddressType.P2Tr: |
| | 0 | 295 | | // Derive the key for this specific UTXO |
| | 0 | 296 | | signingExtKey = |
| | 0 | 297 | | _secureKeyManager.GetDepositP2TrKeyAtIndex( |
| | 0 | 298 | | utxo.WalletAddress.Index, utxo.WalletAddress.IsChange); |
| | 0 | 299 | | var rootKey = ExtKey.CreateFromBytes(signingExtKey).PrivateKey; |
| | 0 | 300 | | // For P2TR (Taproot): OP_1 <32-byte-taproot-output> |
| | 0 | 301 | | taprootKeyPair = rootKey.CreateTaprootKeyPair(); |
| | 0 | 302 | | scriptPubKey = taprootKeyPair.PubKey.ScriptPubKey; |
| | 0 | 303 | | break; |
| | | 304 | | |
| | | 305 | | default: |
| | 0 | 306 | | throw new SignerException($"Unsupported address type {utxo.AddressType} for input {i}", |
| | 0 | 307 | | channelId); |
| | | 308 | | } |
| | 0 | 309 | | |
| | 0 | 310 | | signingKeys[i] = signingKey; |
| | 0 | 311 | | taprootKeyPairs[i] = taprootKeyPair; |
| | 0 | 312 | | prevOuts[i] = new TxOut(new Money(utxo.Amount.Satoshi), scriptPubKey); |
| | 0 | 313 | | } |
| | 0 | 314 | | catch (Exception ex) |
| | | 315 | | { |
| | 0 | 316 | | _logger.LogError(ex, "Failed to sign input {InputIndex} in funding transaction", i); |
| | 0 | 317 | | throw new SignerException( |
| | 0 | 318 | | $"Failed to sign input {i}", |
| | 0 | 319 | | channelId, ex, "Signing error"); |
| | | 320 | | } |
| | | 321 | | } |
| | | 322 | | |
| | 0 | 323 | | for (var i = 0; i < nBitcoinTx.Inputs.Count; i++) |
| | | 324 | | { |
| | | 325 | | try |
| | | 326 | | { |
| | 0 | 327 | | var utxo = utxos[i]; |
| | 0 | 328 | | var signingKey = signingKeys[i]; |
| | 0 | 329 | | var taprootKeyPair = taprootKeyPairs[i]; |
| | 0 | 330 | | var prevOut = prevOuts[i]; |
| | | 331 | | |
| | 0 | 332 | | switch (utxo.AddressType) |
| | | 333 | | { |
| | | 334 | | // Sign based on the address type |
| | | 335 | | case AddressType.P2Wpkh: |
| | 0 | 336 | | if (signingKey is null) |
| | 0 | 337 | | throw new SignerException($"Missing signing key for P2WPKH input {i}", channelId); |
| | | 338 | | |
| | | 339 | | // Sign P2WPKH input |
| | 0 | 340 | | SignP2WpkhInput(nBitcoinTx, i, signingKey, prevOut); |
| | 0 | 341 | | break; |
| | | 342 | | case AddressType.P2Tr: |
| | 0 | 343 | | if (taprootKeyPair is null) |
| | 0 | 344 | | throw new SignerException($"Missing taproot key pair for P2TR input {i}", channelId); |
| | | 345 | | |
| | | 346 | | // Sign P2TR (Taproot) input - key path spend |
| | 0 | 347 | | SignP2TrInput(nBitcoinTx, i, taprootKeyPair, prevOuts); |
| | 0 | 348 | | break; |
| | | 349 | | default: |
| | 0 | 350 | | throw new SignerException($"Unsupported address type {utxo.AddressType} for input {i}", |
| | 0 | 351 | | channelId); |
| | | 352 | | } |
| | | 353 | | |
| | 0 | 354 | | signedInputCount++; |
| | | 355 | | |
| | 0 | 356 | | _logger.LogTrace("Signed input {InputIndex} for funding transaction", i); |
| | 0 | 357 | | } |
| | 0 | 358 | | catch (Exception ex) |
| | | 359 | | { |
| | 0 | 360 | | _logger.LogError(ex, "Failed to sign input {InputIndex} in funding transaction", i); |
| | 0 | 361 | | throw new SignerException( |
| | 0 | 362 | | $"Failed to sign input {i}", |
| | 0 | 363 | | channelId, ex, "Signing error"); |
| | | 364 | | } |
| | | 365 | | } |
| | | 366 | | |
| | 0 | 367 | | if (signedInputCount == 0) |
| | 0 | 368 | | throw new SignerException("No inputs were successfully signed", channelId, "Signing failed"); |
| | | 369 | | |
| | | 370 | | // Update the transaction bytes in the SignedTransaction |
| | 0 | 371 | | unsignedTransaction.RawTxBytes = nBitcoinTx.ToBytes(); |
| | | 372 | | |
| | 0 | 373 | | _logger.LogInformation( |
| | 0 | 374 | | "Successfully signed {SignedCount}/{TotalCount} inputs for funding transaction {TxId}", |
| | 0 | 375 | | signedInputCount, nBitcoinTx.Inputs.Count, nBitcoinTx.GetHash()); |
| | | 376 | | |
| | 0 | 377 | | return signedInputCount == nBitcoinTx.Inputs.Count; |
| | | 378 | | } |
| | 0 | 379 | | catch (SignerException) |
| | | 380 | | { |
| | 0 | 381 | | throw; |
| | | 382 | | } |
| | 0 | 383 | | catch (Exception e) |
| | | 384 | | { |
| | 0 | 385 | | throw new SignerException($"Exception during funding transaction signing for TxId {nBitcoinTx.GetHash()}", |
| | 0 | 386 | | channelId, e); |
| | | 387 | | } |
| | 0 | 388 | | } |
| | | 389 | | |
| | | 390 | | /// <inheritdoc /> |
| | | 391 | | public CompactSignature SignChannelTransaction(ChannelId channelId, SignedTransaction unsignedTransaction) |
| | | 392 | | { |
| | 64 | 393 | | if (_logger.IsEnabled(LogLevel.Trace)) |
| | 0 | 394 | | _logger.LogTrace("Signing transaction for channel {ChannelId} with TxId {TxId}", channelId, |
| | 0 | 395 | | unsignedTransaction.TxId); |
| | | 396 | | |
| | 64 | 397 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 398 | | throw new InvalidOperationException($"Channel {channelId} not registered with signer"); |
| | | 399 | | |
| | | 400 | | Transaction nBitcoinTx; |
| | | 401 | | try |
| | | 402 | | { |
| | 64 | 403 | | nBitcoinTx = Transaction.Load(unsignedTransaction.RawTxBytes, _network); |
| | 64 | 404 | | } |
| | 0 | 405 | | catch (Exception ex) |
| | | 406 | | { |
| | 0 | 407 | | throw new ArgumentException( |
| | 0 | 408 | | $"Failed to load transaction from RawTxBytes. TxId hint: {unsignedTransaction.TxId}", ex); |
| | | 409 | | } |
| | | 410 | | |
| | | 411 | | try |
| | | 412 | | { |
| | | 413 | | // Build the funding output using the channel's signing info |
| | 64 | 414 | | var fundingOutputInfo = new FundingOutputInfo(signingInfo.FundingSatoshis, signingInfo.LocalFundingPubKey, |
| | 64 | 415 | | signingInfo.RemoteFundingPubKey, signingInfo.FundingTxId, |
| | 64 | 416 | | signingInfo.FundingOutputIndex); |
| | | 417 | | |
| | 64 | 418 | | var fundingOutput = _fundingOutputBuilder.Build(fundingOutputInfo); |
| | 64 | 419 | | var spentOutput = fundingOutput.ToTxOut(); |
| | | 420 | | |
| | | 421 | | // Get the signature hash for SegWit |
| | 64 | 422 | | var signatureHash = nBitcoinTx.GetSignatureHash(fundingOutput.RedeemScript, 0, SigHash.All, spentOutput, |
| | 64 | 423 | | HashVersion.WitnessV0); |
| | | 424 | | |
| | | 425 | | // Get the funding private key |
| | 64 | 426 | | using var fundingPrivateKey = GenerateFundingPrivateKey(signingInfo.ChannelKeyIndex); |
| | | 427 | | |
| | 64 | 428 | | var signature = fundingPrivateKey.Sign(signatureHash, new SigningOptions(SigHash.All, false)); |
| | | 429 | | |
| | 64 | 430 | | return signature.Signature.MakeCanonical().ToCompact(); |
| | | 431 | | } |
| | 0 | 432 | | catch (Exception ex) |
| | | 433 | | { |
| | 0 | 434 | | throw new InvalidOperationException( |
| | 0 | 435 | | $"Exception during signature verification for TxId {nBitcoinTx.GetHash()}", ex); |
| | | 436 | | } |
| | 64 | 437 | | } |
| | | 438 | | |
| | | 439 | | /// <inheritdoc /> |
| | | 440 | | public void ValidateSignature(ChannelId channelId, CompactSignature signature, |
| | | 441 | | SignedTransaction unsignedTransaction) |
| | | 442 | | { |
| | 72 | 443 | | if (_logger.IsEnabled(LogLevel.Trace)) |
| | 0 | 444 | | _logger.LogTrace("Validating signature for channel {ChannelId} with TxId {TxId}", channelId, |
| | 0 | 445 | | unsignedTransaction.TxId); |
| | | 446 | | |
| | 72 | 447 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 4 | 448 | | throw new SignerException("Channel not registered with signer", channelId, "Internal error"); |
| | | 449 | | |
| | | 450 | | Transaction nBitcoinTx; |
| | | 451 | | try |
| | | 452 | | { |
| | 68 | 453 | | nBitcoinTx = Transaction.Load(unsignedTransaction.RawTxBytes, _network); |
| | 68 | 454 | | } |
| | 0 | 455 | | catch (Exception e) |
| | | 456 | | { |
| | 0 | 457 | | throw new SignerException("Failed to load transaction from RawTxBytes", channelId, e, "Internal error"); |
| | | 458 | | } |
| | | 459 | | |
| | | 460 | | PubKey pubKey; |
| | | 461 | | try |
| | | 462 | | { |
| | 68 | 463 | | pubKey = new PubKey(signingInfo.RemoteFundingPubKey); |
| | 68 | 464 | | } |
| | 0 | 465 | | catch (Exception e) |
| | | 466 | | { |
| | 0 | 467 | | throw new SignerException("Failed to parse public key from CompactPubKey", channelId, e, "Internal error"); |
| | | 468 | | } |
| | | 469 | | |
| | | 470 | | ECDSASignature txSignature; |
| | | 471 | | try |
| | | 472 | | { |
| | 68 | 473 | | if (!ECDSASignature.TryParseFromCompact(signature, out txSignature)) |
| | 0 | 474 | | throw new SignerException("Failed to parse compact signature", channelId, "Signature format error"); |
| | | 475 | | |
| | 68 | 476 | | if (!txSignature.IsLowS) |
| | 0 | 477 | | throw new SignerException("Signature is not low S", channelId, |
| | 0 | 478 | | "Signature is malleable"); |
| | 68 | 479 | | } |
| | 0 | 480 | | catch (Exception e) |
| | | 481 | | { |
| | 0 | 482 | | throw new SignerException("Failed to parse DER signature", channelId, e, |
| | 0 | 483 | | "Signature format error"); |
| | | 484 | | } |
| | | 485 | | |
| | | 486 | | try |
| | | 487 | | { |
| | | 488 | | // Build the funding output using the channel's signing info |
| | 68 | 489 | | var fundingOutputInfo = new FundingOutputInfo(signingInfo.FundingSatoshis, signingInfo.LocalFundingPubKey, |
| | 68 | 490 | | signingInfo.RemoteFundingPubKey, signingInfo.FundingTxId, |
| | 68 | 491 | | signingInfo.FundingOutputIndex); |
| | | 492 | | |
| | 68 | 493 | | var fundingOutput = _fundingOutputBuilder.Build(fundingOutputInfo); |
| | 68 | 494 | | var spentOutput = fundingOutput.ToTxOut(); |
| | | 495 | | |
| | 68 | 496 | | var signatureHash = |
| | 68 | 497 | | nBitcoinTx.GetSignatureHash(fundingOutput.RedeemScript, 0, SigHash.All, spentOutput, |
| | 68 | 498 | | HashVersion.WitnessV0); |
| | | 499 | | |
| | 68 | 500 | | if (!pubKey.Verify(signatureHash, txSignature)) |
| | 0 | 501 | | throw new SignerException("Peer signature is invalid", channelId, "Invalid signature provided"); |
| | 68 | 502 | | } |
| | 0 | 503 | | catch (Exception e) |
| | | 504 | | { |
| | 0 | 505 | | throw new SignerException("Exception during signature verification", channelId, e, |
| | 0 | 506 | | "Signature verification error"); |
| | | 507 | | } |
| | 68 | 508 | | } |
| | | 509 | | |
| | | 510 | | protected virtual Key GenerateFundingPrivateKey(uint channelKeyIndex) |
| | | 511 | | { |
| | 0 | 512 | | var channelExtKey = _secureKeyManager.GetChannelKeyAtIndex(channelKeyIndex); |
| | 0 | 513 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | | 514 | | |
| | 0 | 515 | | return GenerateFundingPrivateKey(channelKey); |
| | | 516 | | } |
| | | 517 | | |
| | | 518 | | private static Key GenerateFundingPrivateKey(ExtKey extKey) |
| | | 519 | | { |
| | 0 | 520 | | return extKey.Derive(FundingDerivationIndex, true).PrivateKey; |
| | | 521 | | } |
| | | 522 | | |
| | | 523 | | /// <summary> |
| | | 524 | | /// Sign a P2WPKH (Pay-to-Witness-PubKey-Hash) input |
| | | 525 | | /// </summary> |
| | | 526 | | private static void SignP2WpkhInput(Transaction tx, int inputIndex, Key signingKey, TxOut prevOut) |
| | | 527 | | { |
| | | 528 | | // For P2WPKH, the scriptCode is the P2PKH script: OP_DUP OP_HASH160 <pubkeyhash> OP_EQUALVERIFY OP_CHECKSIG |
| | 0 | 529 | | var scriptCode = signingKey.PubKey.Hash.ScriptPubKey; |
| | | 530 | | |
| | | 531 | | // Get the signature hash for SegWit v0 |
| | 0 | 532 | | var sigHash = |
| | 0 | 533 | | tx.GetSignatureHash(scriptCode, inputIndex, SigHash.All, prevOut, HashVersion.WitnessV0); |
| | | 534 | | |
| | | 535 | | // Sign the hash |
| | 0 | 536 | | var transactionSignature = signingKey.Sign(sigHash, new SigningOptions(SigHash.All, false)); |
| | | 537 | | |
| | | 538 | | // For P2WPKH, witness is: <signature> <pubkey> |
| | 0 | 539 | | var witness = new WitScript( |
| | 0 | 540 | | Op.GetPushOp(transactionSignature.ToBytes()), |
| | 0 | 541 | | Op.GetPushOp(signingKey.PubKey.ToBytes())); |
| | | 542 | | |
| | 0 | 543 | | tx.Inputs[inputIndex].WitScript = witness; |
| | 0 | 544 | | } |
| | | 545 | | |
| | | 546 | | /// <summary> |
| | | 547 | | /// Sign a P2TR (Pay-to-Taproot) input using the key path spend |
| | | 548 | | /// </summary> |
| | | 549 | | /// <remarks>For Taproot, we use BIP341 signing</remarks> |
| | | 550 | | private static void SignP2TrInput(Transaction tx, int inputIndex, TaprootKeyPair taprootKeyPair, TxOut[] prevOuts) |
| | | 551 | | { |
| | | 552 | | // Create the TaprootExecutionData |
| | 0 | 553 | | var taprootExecutionData = new TaprootExecutionData(inputIndex) |
| | 0 | 554 | | { |
| | 0 | 555 | | SigHash = TaprootSigHash.All |
| | 0 | 556 | | }; |
| | | 557 | | |
| | | 558 | | // Calculate the signature hash using Taproot rules (BIP341) |
| | 0 | 559 | | var sigHash = tx.GetSignatureHashTaproot(prevOuts.ToArray(), taprootExecutionData); |
| | | 560 | | |
| | | 561 | | // Sign with Schnorr signature (BIP340) |
| | 0 | 562 | | var taprootSignature = taprootKeyPair.SignTaprootKeySpend(sigHash, TaprootSigHash.All); |
| | | 563 | | |
| | | 564 | | // For key path spend, witness is just: <signature> |
| | 0 | 565 | | tx.Inputs[inputIndex].WitScript = new WitScript(Op.GetPushOp(taprootSignature.ToBytes())); |
| | 0 | 566 | | } |
| | | 567 | | } |