| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using NBitcoin; |
| | | 4 | | using NBitcoin.Crypto; |
| | | 5 | | using NLightning.Domain.Bitcoin.Transactions.Outputs; |
| | | 6 | | |
| | | 7 | | namespace NLightning.Infrastructure.Bitcoin.Signers; |
| | | 8 | | |
| | | 9 | | using Builders; |
| | | 10 | | using Domain.Bitcoin.Interfaces; |
| | | 11 | | using Domain.Bitcoin.ValueObjects; |
| | | 12 | | using Domain.Channels.ValueObjects; |
| | | 13 | | using Domain.Crypto.Constants; |
| | | 14 | | using Domain.Crypto.ValueObjects; |
| | | 15 | | using Domain.Exceptions; |
| | | 16 | | using Domain.Node.Options; |
| | | 17 | | using Domain.Protocol.Interfaces; |
| | | 18 | | |
| | | 19 | | public class LocalLightningSigner : ILightningSigner |
| | | 20 | | { |
| | | 21 | | private const int FundingDerivationIndex = 0; // m/0' is the funding key |
| | | 22 | | private const int RevocationDerivationIndex = 1; // m/1' is the revocation key |
| | | 23 | | private const int PaymentDerivationIndex = 2; // m/2' is the payment key |
| | | 24 | | private const int DelayedPaymentDerivationIndex = 3; // m/3' is the delayed payment key |
| | | 25 | | private const int HtlcDerivationIndex = 4; // m/4' is the HTLC key |
| | | 26 | | private const int PerCommitmentSeedDerivationIndex = 5; // m/5' is the per-commitment seed |
| | | 27 | | |
| | | 28 | | private readonly ISecureKeyManager _secureKeyManager; |
| | | 29 | | private readonly IFundingOutputBuilder _fundingOutputBuilder; |
| | | 30 | | private readonly IKeyDerivationService _keyDerivationService; |
| | 72 | 31 | | private readonly ConcurrentDictionary<ChannelId, ChannelSigningInfo> _channelSigningInfo = new(); |
| | | 32 | | private readonly ILogger<LocalLightningSigner> _logger; |
| | | 33 | | private readonly Network _network; |
| | | 34 | | |
| | 72 | 35 | | public LocalLightningSigner(IFundingOutputBuilder fundingOutputBuilder, IKeyDerivationService keyDerivationService, |
| | 72 | 36 | | ILogger<LocalLightningSigner> logger, NodeOptions nodeOptions, |
| | 72 | 37 | | ISecureKeyManager secureKeyManager) |
| | | 38 | | { |
| | 72 | 39 | | _fundingOutputBuilder = fundingOutputBuilder; |
| | 72 | 40 | | _keyDerivationService = keyDerivationService; |
| | 72 | 41 | | _logger = logger; |
| | 72 | 42 | | _secureKeyManager = secureKeyManager; |
| | | 43 | | |
| | 72 | 44 | | _network = Network.GetNetwork(nodeOptions.BitcoinNetwork) ?? |
| | 72 | 45 | | throw new ArgumentException("Invalid Bitcoin network specified", nameof(nodeOptions)); |
| | | 46 | | |
| | | 47 | | // TODO: Load channel key data from database |
| | 72 | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <inheritdoc /> |
| | | 51 | | public uint CreateNewChannel(out ChannelBasepoints basepoints, out CompactPubKey firstPerCommitmentPoint) |
| | | 52 | | { |
| | | 53 | | // Generate a new key for this channel |
| | 0 | 54 | | var channelPrivExtKey = _secureKeyManager.GetNextKey(out var index); |
| | 0 | 55 | | var channelKey = ExtKey.CreateFromBytes(channelPrivExtKey); |
| | | 56 | | |
| | | 57 | | // Generate Lightning basepoints using proper BIP32 derivation paths |
| | 0 | 58 | | using var localFundingSecret = GenerateFundingPrivateKey(channelKey); |
| | 0 | 59 | | using var localRevocationSecret = channelKey.Derive(RevocationDerivationIndex, true).PrivateKey; |
| | 0 | 60 | | using var localPaymentSecret = channelKey.Derive(PaymentDerivationIndex, true).PrivateKey; |
| | 0 | 61 | | using var localDelayedPaymentSecret = channelKey.Derive(DelayedPaymentDerivationIndex, true).PrivateKey; |
| | 0 | 62 | | using var localHtlcSecret = channelKey.Derive(HtlcDerivationIndex, true).PrivateKey; |
| | 0 | 63 | | using var perCommitmentSeed = channelKey.Derive(PerCommitmentSeedDerivationIndex, true).PrivateKey; |
| | | 64 | | |
| | | 65 | | // Generate static basepoints (these don't change per commitment) |
| | 0 | 66 | | basepoints = new ChannelBasepoints( |
| | 0 | 67 | | localFundingSecret.PubKey.ToBytes(), |
| | 0 | 68 | | localRevocationSecret.PubKey.ToBytes(), |
| | 0 | 69 | | localPaymentSecret.PubKey.ToBytes(), |
| | 0 | 70 | | localDelayedPaymentSecret.PubKey.ToBytes(), |
| | 0 | 71 | | localHtlcSecret.PubKey.ToBytes() |
| | 0 | 72 | | ); |
| | | 73 | | |
| | | 74 | | // Generate the first per-commitment point |
| | 0 | 75 | | var firstPerCommitmentSecretBytes = _keyDerivationService |
| | 0 | 76 | | .GeneratePerCommitmentSecret(perCommitmentSeed.ToBytes(), CryptoConstants.FirstPerCommitmentIndex); |
| | 0 | 77 | | using var firstPerCommitmentSecret = new Key(firstPerCommitmentSecretBytes); |
| | 0 | 78 | | firstPerCommitmentPoint = firstPerCommitmentSecret.PubKey.ToBytes(); |
| | | 79 | | |
| | 0 | 80 | | return index; |
| | 0 | 81 | | } |
| | | 82 | | |
| | | 83 | | /// <inheritdoc /> |
| | | 84 | | public ChannelBasepoints GetChannelBasepoints(uint channelKeyIndex) |
| | | 85 | | { |
| | 0 | 86 | | _logger.LogTrace("Generating channel basepoints for key index {ChannelKeyIndex}", channelKeyIndex); |
| | | 87 | | |
| | | 88 | | // Recreate the basepoints from the channel key index |
| | 0 | 89 | | var channelExtKey = _secureKeyManager.GetKeyAtIndex(channelKeyIndex); |
| | 0 | 90 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | | 91 | | |
| | 0 | 92 | | using var localFundingSecret = channelKey.Derive(FundingDerivationIndex, true).PrivateKey; |
| | 0 | 93 | | using var localRevocationSecret = channelKey.Derive(RevocationDerivationIndex, true).PrivateKey; |
| | 0 | 94 | | using var localPaymentSecret = channelKey.Derive(PaymentDerivationIndex, true).PrivateKey; |
| | 0 | 95 | | using var localDelayedPaymentSecret = channelKey.Derive(DelayedPaymentDerivationIndex, true).PrivateKey; |
| | 0 | 96 | | using var localHtlcSecret = channelKey.Derive(HtlcDerivationIndex, true).PrivateKey; |
| | | 97 | | |
| | 0 | 98 | | return new ChannelBasepoints( |
| | 0 | 99 | | localFundingSecret.PubKey.ToBytes(), |
| | 0 | 100 | | localRevocationSecret.PubKey.ToBytes(), |
| | 0 | 101 | | localPaymentSecret.PubKey.ToBytes(), |
| | 0 | 102 | | localDelayedPaymentSecret.PubKey.ToBytes(), |
| | 0 | 103 | | localHtlcSecret.PubKey.ToBytes() |
| | 0 | 104 | | ); |
| | 0 | 105 | | } |
| | | 106 | | |
| | | 107 | | /// <inheritdoc /> |
| | | 108 | | public ChannelBasepoints GetChannelBasepoints(ChannelId channelId) |
| | | 109 | | { |
| | 0 | 110 | | _logger.LogTrace("Retrieving channel basepoints for channel {ChannelId}", channelId); |
| | | 111 | | |
| | 0 | 112 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 113 | | throw new InvalidOperationException($"Channel {channelId} not registered"); |
| | | 114 | | |
| | 0 | 115 | | return GetChannelBasepoints(signingInfo.ChannelKeyIndex); |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | /// <inheritdoc /> |
| | 0 | 119 | | public CompactPubKey GetNodePublicKey() => _secureKeyManager.GetNodeKeyPair().CompactPubKey; |
| | | 120 | | |
| | | 121 | | /// <inheritdoc /> |
| | | 122 | | public CompactPubKey GetPerCommitmentPoint(uint channelKeyIndex, ulong commitmentNumber) |
| | | 123 | | { |
| | 0 | 124 | | _logger.LogTrace( |
| | 0 | 125 | | "Generating per-commitment point for channel key index {ChannelKeyIndex} and commitment number {CommitmentNu |
| | 0 | 126 | | channelKeyIndex, commitmentNumber); |
| | | 127 | | |
| | | 128 | | // Derive the per-commitment seed from the channel key |
| | 0 | 129 | | var channelExtKey = _secureKeyManager.GetKeyAtIndex(channelKeyIndex); |
| | 0 | 130 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | 0 | 131 | | using var perCommitmentSeed = channelKey.Derive(5).PrivateKey; |
| | | 132 | | |
| | 0 | 133 | | var perCommitmentSecret = |
| | 0 | 134 | | _keyDerivationService.GeneratePerCommitmentSecret(perCommitmentSeed.ToBytes(), commitmentNumber); |
| | | 135 | | |
| | 0 | 136 | | var perCommitmentPoint = new Key(perCommitmentSecret).PubKey; |
| | 0 | 137 | | return perCommitmentPoint.ToBytes(); |
| | 0 | 138 | | } |
| | | 139 | | |
| | | 140 | | /// <inheritdoc /> |
| | | 141 | | public CompactPubKey GetPerCommitmentPoint(ChannelId channelId, ulong commitmentNumber) |
| | | 142 | | { |
| | 0 | 143 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 144 | | throw new InvalidOperationException($"Channel {channelId} not registered"); |
| | | 145 | | |
| | 0 | 146 | | return GetPerCommitmentPoint(signingInfo.ChannelKeyIndex, commitmentNumber); |
| | | 147 | | } |
| | | 148 | | |
| | | 149 | | /// <inheritdoc /> |
| | | 150 | | public void RegisterChannel(ChannelId channelId, ChannelSigningInfo signingInfo) |
| | | 151 | | { |
| | 68 | 152 | | _logger.LogTrace("Registering channel {ChannelId} with signing info", channelId); |
| | | 153 | | |
| | 68 | 154 | | _channelSigningInfo.TryAdd(channelId, signingInfo); |
| | 68 | 155 | | } |
| | | 156 | | |
| | | 157 | | /// <inheritdoc /> |
| | | 158 | | public Secret ReleasePerCommitmentSecret(uint channelKeyIndex, ulong commitmentNumber) |
| | | 159 | | { |
| | 0 | 160 | | _logger.LogTrace( |
| | 0 | 161 | | "Releasing per-commitment secret for channel key index {ChannelKeyIndex} and commitment number {CommitmentNu |
| | 0 | 162 | | channelKeyIndex, commitmentNumber); |
| | | 163 | | |
| | | 164 | | // Derive the per-commitment seed from the channel key |
| | 0 | 165 | | var channelExtKey = _secureKeyManager.GetKeyAtIndex(channelKeyIndex); |
| | 0 | 166 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | 0 | 167 | | using var perCommitmentSeed = channelKey.Derive(5).PrivateKey; |
| | | 168 | | |
| | 0 | 169 | | return _keyDerivationService.GeneratePerCommitmentSecret( |
| | 0 | 170 | | perCommitmentSeed.ToBytes(), commitmentNumber); |
| | 0 | 171 | | } |
| | | 172 | | |
| | | 173 | | /// <inheritdoc /> |
| | | 174 | | public Secret ReleasePerCommitmentSecret(ChannelId channelId, ulong commitmentNumber) |
| | | 175 | | { |
| | 0 | 176 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 177 | | throw new InvalidOperationException($"Channel {channelId} not registered"); |
| | | 178 | | |
| | 0 | 179 | | return ReleasePerCommitmentSecret(signingInfo.ChannelKeyIndex, commitmentNumber); |
| | | 180 | | } |
| | | 181 | | |
| | | 182 | | /// <inheritdoc /> |
| | | 183 | | public CompactSignature SignTransaction(ChannelId channelId, SignedTransaction unsignedTransaction) |
| | | 184 | | { |
| | 64 | 185 | | _logger.LogTrace("Signing transaction for channel {ChannelId} with TxId {TxId}", channelId, |
| | 64 | 186 | | unsignedTransaction.TxId); |
| | | 187 | | |
| | 64 | 188 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 0 | 189 | | throw new InvalidOperationException($"Channel {channelId} not registered with signer"); |
| | | 190 | | |
| | | 191 | | Transaction nBitcoinTx; |
| | | 192 | | try |
| | | 193 | | { |
| | 64 | 194 | | nBitcoinTx = Transaction.Load(unsignedTransaction.RawTxBytes, _network); |
| | 64 | 195 | | } |
| | 0 | 196 | | catch (Exception ex) |
| | | 197 | | { |
| | 0 | 198 | | throw new ArgumentException( |
| | 0 | 199 | | $"Failed to load transaction from RawTxBytes. TxId hint: {unsignedTransaction.TxId}", ex); |
| | | 200 | | } |
| | | 201 | | |
| | | 202 | | try |
| | | 203 | | { |
| | | 204 | | // Build the funding output using the channel's signing info |
| | 64 | 205 | | var fundingOutputInfo = new FundingOutputInfo(signingInfo.FundingSatoshis, signingInfo.LocalFundingPubKey, |
| | 64 | 206 | | signingInfo.RemoteFundingPubKey, signingInfo.FundingTxId, |
| | 64 | 207 | | signingInfo.FundingOutputIndex); |
| | | 208 | | |
| | 64 | 209 | | var fundingOutput = _fundingOutputBuilder.Build(fundingOutputInfo); |
| | 64 | 210 | | var spentOutput = fundingOutput.ToTxOut(); |
| | | 211 | | |
| | | 212 | | // Get the signature hash for SegWit |
| | 64 | 213 | | var signatureHash = nBitcoinTx.GetSignatureHash(fundingOutput.RedeemScript, |
| | 64 | 214 | | (int)signingInfo.FundingOutputIndex, SigHash.All, |
| | 64 | 215 | | spentOutput, HashVersion.WitnessV0); |
| | | 216 | | |
| | | 217 | | // Get the funding private key |
| | 64 | 218 | | using var fundingPrivateKey = GenerateFundingPrivateKey(signingInfo.ChannelKeyIndex); |
| | | 219 | | |
| | 64 | 220 | | var signature = fundingPrivateKey.Sign(signatureHash, new SigningOptions(SigHash.All, false)); |
| | | 221 | | |
| | 64 | 222 | | return signature.Signature.MakeCanonical().ToCompact(); |
| | | 223 | | } |
| | 0 | 224 | | catch (Exception ex) |
| | | 225 | | { |
| | 0 | 226 | | throw new InvalidOperationException( |
| | 0 | 227 | | $"Exception during signature verification for TxId {nBitcoinTx.GetHash()}", ex); |
| | | 228 | | } |
| | 64 | 229 | | } |
| | | 230 | | |
| | | 231 | | /// <inheritdoc /> |
| | | 232 | | public void ValidateSignature(ChannelId channelId, CompactSignature signature, |
| | | 233 | | SignedTransaction unsignedTransaction) |
| | | 234 | | { |
| | 72 | 235 | | _logger.LogTrace("Validating signature for channel {ChannelId} with TxId {TxId}", channelId, |
| | 72 | 236 | | unsignedTransaction.TxId); |
| | | 237 | | |
| | 72 | 238 | | if (!_channelSigningInfo.TryGetValue(channelId, out var signingInfo)) |
| | 4 | 239 | | throw new SignerException("Channel not registered with signer", channelId, "Internal error"); |
| | | 240 | | |
| | | 241 | | Transaction nBitcoinTx; |
| | | 242 | | try |
| | | 243 | | { |
| | 68 | 244 | | nBitcoinTx = Transaction.Load(unsignedTransaction.RawTxBytes, _network); |
| | 68 | 245 | | } |
| | 0 | 246 | | catch (Exception e) |
| | | 247 | | { |
| | 0 | 248 | | throw new SignerException("Failed to load transaction from RawTxBytes", channelId, e, "Internal error"); |
| | | 249 | | } |
| | | 250 | | |
| | | 251 | | PubKey pubKey; |
| | | 252 | | try |
| | | 253 | | { |
| | 68 | 254 | | pubKey = new PubKey(signingInfo.RemoteFundingPubKey); |
| | 68 | 255 | | } |
| | 0 | 256 | | catch (Exception e) |
| | | 257 | | { |
| | 0 | 258 | | throw new SignerException("Failed to parse public key from CompactPubKey", channelId, e, "Internal error"); |
| | | 259 | | } |
| | | 260 | | |
| | | 261 | | ECDSASignature txSignature; |
| | | 262 | | try |
| | | 263 | | { |
| | 68 | 264 | | if (!ECDSASignature.TryParseFromCompact(signature, out txSignature)) |
| | 0 | 265 | | throw new SignerException("Failed to parse compact signature", channelId, "Signature format error"); |
| | | 266 | | |
| | 68 | 267 | | if (!txSignature.IsLowS) |
| | 0 | 268 | | throw new SignerException("Signature is not low S", channelId, |
| | 0 | 269 | | "Signature is malleable"); |
| | 68 | 270 | | } |
| | 0 | 271 | | catch (Exception e) |
| | | 272 | | { |
| | 0 | 273 | | throw new SignerException("Failed to parse DER signature", channelId, e, |
| | 0 | 274 | | "Signature format error"); |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | try |
| | | 278 | | { |
| | | 279 | | // Build the funding output using the channel's signing info |
| | 68 | 280 | | var fundingOutputInfo = new FundingOutputInfo(signingInfo.FundingSatoshis, signingInfo.LocalFundingPubKey, |
| | 68 | 281 | | signingInfo.RemoteFundingPubKey) |
| | 68 | 282 | | { |
| | 68 | 283 | | TransactionId = signingInfo.FundingTxId, |
| | 68 | 284 | | Index = signingInfo.FundingOutputIndex |
| | 68 | 285 | | }; |
| | | 286 | | |
| | 68 | 287 | | var fundingOutput = _fundingOutputBuilder.Build(fundingOutputInfo); |
| | 68 | 288 | | var spentOutput = fundingOutput.ToTxOut(); |
| | | 289 | | |
| | 68 | 290 | | var signatureHash = nBitcoinTx.GetSignatureHash(fundingOutput.RedeemScript, |
| | 68 | 291 | | (int)signingInfo.FundingOutputIndex, SigHash.All, |
| | 68 | 292 | | spentOutput, HashVersion.WitnessV0); |
| | | 293 | | |
| | 68 | 294 | | if (!pubKey.Verify(signatureHash, txSignature)) |
| | 0 | 295 | | throw new SignerException("Peer signature is invalid", channelId, "Invalid signature provided"); |
| | 68 | 296 | | } |
| | 0 | 297 | | catch (Exception e) |
| | | 298 | | { |
| | 0 | 299 | | throw new SignerException("Exception during signature verification", channelId, e, |
| | 0 | 300 | | "Signature verification error"); |
| | | 301 | | } |
| | 68 | 302 | | } |
| | | 303 | | |
| | | 304 | | protected virtual Key GenerateFundingPrivateKey(uint channelKeyIndex) |
| | | 305 | | { |
| | 0 | 306 | | var channelExtKey = _secureKeyManager.GetKeyAtIndex(channelKeyIndex); |
| | 0 | 307 | | var channelKey = ExtKey.CreateFromBytes(channelExtKey); |
| | | 308 | | |
| | 0 | 309 | | return GenerateFundingPrivateKey(channelKey); |
| | | 310 | | } |
| | | 311 | | |
| | | 312 | | private Key GenerateFundingPrivateKey(ExtKey extKey) |
| | | 313 | | { |
| | 0 | 314 | | return extKey.Derive(FundingDerivationIndex, true).PrivateKey; |
| | | 315 | | } |
| | | 316 | | } |