| | 1 | | namespace NLightning.Domain.Crypto.ValueObjects; |
| | 2 | |
|
| | 3 | | using Constants; |
| | 4 | | using Utils.Extensions; |
| | 5 | |
|
| | 6 | | public readonly struct CompactPubKey : IEquatable<CompactPubKey> |
| | 7 | | { |
| | 8 | | private readonly byte[] _value; |
| | 9 | |
|
| | 10 | | public CompactPubKey(byte[] value) |
| | 11 | | { |
| 2332 | 12 | | if (value.Length != CryptoConstants.CompactPubkeyLen) |
| 0 | 13 | | throw new ArgumentException("PublicKey cannot be empty.", nameof(value)); |
| | 14 | |
|
| 2332 | 15 | | if (value[0] != 0x02 && value[0] != 0x03) |
| 0 | 16 | | throw new ArgumentException("Invalid CompactPubKey format. The first byte must be 0x02 or 0x03.", |
| 0 | 17 | | nameof(value)); |
| | 18 | |
|
| 2332 | 19 | | _value = value; |
| 2332 | 20 | | } |
| | 21 | |
|
| 1904 | 22 | | public static implicit operator CompactPubKey(byte[] bytes) => new(bytes); |
| 1080 | 23 | | public static implicit operator byte[](CompactPubKey hash) => hash._value; |
| | 24 | |
|
| 728 | 25 | | public static implicit operator ReadOnlySpan<byte>(CompactPubKey compactPubKey) => compactPubKey._value; |
| | 26 | |
|
| 124 | 27 | | public static implicit operator ReadOnlyMemory<byte>(CompactPubKey compactPubKey) => compactPubKey._value; |
| | 28 | |
|
| | 29 | | public static bool operator !=(CompactPubKey left, CompactPubKey right) |
| | 30 | | { |
| 0 | 31 | | return !left.Equals(right); |
| | 32 | | } |
| | 33 | |
|
| | 34 | | public static bool operator ==(CompactPubKey left, CompactPubKey right) |
| | 35 | | { |
| 0 | 36 | | return left.Equals(right); |
| | 37 | | } |
| | 38 | |
|
| 40 | 39 | | public override string ToString() => Convert.ToHexString(_value).ToLowerInvariant(); |
| | 40 | |
|
| | 41 | | public bool Equals(CompactPubKey other) |
| | 42 | | { |
| | 43 | | // Handle null cases first |
| | 44 | | // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract |
| 124 | 45 | | if (_value is null && other._value is null) |
| 0 | 46 | | return true; |
| | 47 | |
|
| | 48 | | // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract |
| 124 | 49 | | if (_value is null || other._value is null) |
| 0 | 50 | | return false; |
| | 51 | |
|
| 124 | 52 | | return _value.SequenceEqual(other._value); |
| | 53 | | } |
| | 54 | |
|
| | 55 | | public override bool Equals(object? obj) |
| | 56 | | { |
| 44 | 57 | | if (obj is null) |
| 0 | 58 | | return false; |
| | 59 | |
|
| 44 | 60 | | return obj is CompactPubKey other && Equals(other); |
| | 61 | | } |
| | 62 | |
|
| | 63 | | public override int GetHashCode() |
| | 64 | | { |
| 96 | 65 | | return _value.GetByteArrayHashCode(); |
| | 66 | | } |
| | 67 | | } |