| | 1 | | namespace NLightning.Domain.Bitcoin.ValueObjects; |
| | 2 | |
|
| | 3 | | using Crypto.Constants; |
| | 4 | | using Utils.Extensions; |
| | 5 | |
|
| | 6 | | public readonly struct TxId : IEquatable<TxId> |
| | 7 | | { |
| | 8 | | private readonly byte[] _value; |
| | 9 | |
|
| 0 | 10 | | public bool IsZero => _value.SequenceEqual(Zero._value); |
| 0 | 11 | | public bool IsOne => _value.SequenceEqual(One._value); |
| | 12 | |
|
| | 13 | | public TxId(byte[] hash) |
| | 14 | | { |
| 548 | 15 | | if (hash.Length < CryptoConstants.Sha256HashLen) |
| 0 | 16 | | throw new ArgumentException("TxId cannot be empty.", nameof(hash)); |
| | 17 | |
|
| 548 | 18 | | _value = hash; |
| 548 | 19 | | } |
| | 20 | |
|
| 144 | 21 | | public static TxId Zero => new byte[CryptoConstants.Sha256HashLen]; |
| | 22 | |
|
| 48 | 23 | | public static TxId One => new byte[] |
| 48 | 24 | | { |
| 48 | 25 | | 1, 1, 1, 1, 1, 1, 1, 1, |
| 48 | 26 | | 1, 1, 1, 1, 1, 1, 1, 1, |
| 48 | 27 | | 1, 1, 1, 1, 1, 1, 1, 1, |
| 48 | 28 | | 1, 1, 1, 1, 1, 1, 1, 1, |
| 48 | 29 | | }; |
| | 30 | |
|
| 508 | 31 | | public static implicit operator TxId(byte[] bytes) => new(bytes); |
| 248 | 32 | | public static implicit operator byte[](TxId txId) => txId._value; |
| 0 | 33 | | public static implicit operator ReadOnlyMemory<byte>(TxId compactPubKey) => compactPubKey._value; |
| 0 | 34 | | public static implicit operator ReadOnlySpan<byte>(TxId compactPubKey) => compactPubKey._value; |
| | 35 | |
|
| | 36 | | public static bool operator !=(TxId left, TxId right) |
| | 37 | | { |
| 0 | 38 | | return !left.Equals(right); |
| | 39 | | } |
| | 40 | |
|
| | 41 | | public static bool operator ==(TxId left, TxId right) |
| | 42 | | { |
| 120 | 43 | | return left.Equals(right); |
| | 44 | | } |
| | 45 | |
|
| | 46 | | public bool Equals(TxId other) |
| | 47 | | { |
| | 48 | | // Handle null cases first |
| | 49 | | // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract |
| 132 | 50 | | if (_value is null && other._value is null) |
| 0 | 51 | | return true; |
| | 52 | |
|
| | 53 | | // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract |
| 132 | 54 | | if (_value is null || other._value is null) |
| 0 | 55 | | return false; |
| | 56 | |
|
| 132 | 57 | | return _value.SequenceEqual(other._value); |
| | 58 | | } |
| | 59 | |
|
| | 60 | | public override bool Equals(object? obj) |
| | 61 | | { |
| 8 | 62 | | return obj is TxId other && Equals(other); |
| | 63 | | } |
| | 64 | |
|
| | 65 | | public override int GetHashCode() |
| | 66 | | { |
| 0 | 67 | | return _value.GetByteArrayHashCode(); |
| | 68 | | } |
| | 69 | |
|
| | 70 | | public override string ToString() |
| | 71 | | { |
| 0 | 72 | | return Convert.ToHexString(_value).ToLowerInvariant(); |
| | 73 | | } |
| | 74 | | } |