| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | |
| | | 3 | | namespace NLightning.Infrastructure.Protocol.Factories; |
| | | 4 | | |
| | | 5 | | using Crypto.Hashes; |
| | | 6 | | using Domain.Bitcoin.ValueObjects; |
| | | 7 | | using Domain.Channels.Constants; |
| | | 8 | | using Domain.Channels.ValueObjects; |
| | | 9 | | using Domain.Crypto.ValueObjects; |
| | | 10 | | using Domain.Protocol.Interfaces; |
| | | 11 | | |
| | | 12 | | public class ChannelIdFactory : IChannelIdFactory |
| | | 13 | | { |
| | | 14 | | public ChannelId CreateTemporaryChannelId() |
| | | 15 | | { |
| | 0 | 16 | | return new ChannelId(RandomNumberGenerator.GetBytes(ChannelConstants.ChannelIdLength)); |
| | | 17 | | } |
| | | 18 | | |
| | | 19 | | public ChannelId CreateV1(TxId fundingTxId, ushort fundingOutputIndex) |
| | | 20 | | { |
| | 0 | 21 | | Span<byte> channelId = stackalloc byte[32]; |
| | 0 | 22 | | ((ReadOnlySpan<byte>)fundingTxId).CopyTo(channelId); |
| | | 23 | | |
| | | 24 | | // XOR the last 2 bytes with the funding_output_index |
| | 0 | 25 | | channelId[30] ^= (byte)(fundingOutputIndex >> 8); |
| | 0 | 26 | | channelId[31] ^= (byte)(fundingOutputIndex & 0xFF); |
| | | 27 | | |
| | 0 | 28 | | return new ChannelId(channelId); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | public ChannelId CreateV2(CompactPubKey lesserRevocationBasepoint, CompactPubKey greaterRevocationBasepoint) |
| | | 32 | | { |
| | 4 | 33 | | Span<byte> combined = stackalloc byte[66]; |
| | 4 | 34 | | ((ReadOnlySpan<byte>)lesserRevocationBasepoint).CopyTo(combined); |
| | 4 | 35 | | ((ReadOnlySpan<byte>)greaterRevocationBasepoint).CopyTo(combined[33..]); |
| | | 36 | | |
| | 4 | 37 | | using var hasher = new Sha256(); |
| | 4 | 38 | | hasher.AppendData(combined); |
| | 4 | 39 | | Span<byte> hash = stackalloc byte[32]; |
| | 4 | 40 | | hasher.GetHashAndReset(hash); |
| | 4 | 41 | | return new ChannelId(hash); |
| | 4 | 42 | | } |
| | | 43 | | } |