| | 1 | | using NBitcoin; |
| | 2 | |
|
| | 3 | | namespace NLightning.Bolt11.Models.TaggedFields; |
| | 4 | |
|
| | 5 | | using Constants; |
| | 6 | | using Domain.Utils; |
| | 7 | | using Enums; |
| | 8 | | using Interfaces; |
| | 9 | |
|
| | 10 | | /// <summary> |
| | 11 | | /// Tagged field for the payment hash |
| | 12 | | /// </summary> |
| | 13 | | /// <remarks> |
| | 14 | | /// The payment hash is a 32-byte hash used to identify a payment |
| | 15 | | /// </remarks> |
| | 16 | | /// <seealso cref="ITaggedField"/> |
| | 17 | | internal sealed class PaymentHashTaggedField : ITaggedField |
| | 18 | | { |
| 2132 | 19 | | public TaggedFieldTypes Type => TaggedFieldTypes.PaymentHash; |
| 600 | 20 | | internal uint256 Value { get; } |
| 168 | 21 | | public short Length => TaggedFieldConstants.HashLength; |
| | 22 | |
|
| | 23 | | /// <summary> |
| | 24 | | /// Initializes a new instance of the <see cref="PaymentHashTaggedField"/> class. |
| | 25 | | /// </summary> |
| | 26 | | /// <param name="value">The Description Hash</param> |
| 196 | 27 | | internal PaymentHashTaggedField(uint256 value) |
| | 28 | | { |
| 196 | 29 | | Value = value; |
| 196 | 30 | | } |
| | 31 | |
|
| | 32 | | /// <inheritdoc/> |
| | 33 | | public void WriteToBitWriter(BitWriter bitWriter) |
| | 34 | | { |
| 56 | 35 | | var data = Value.ToBytes(); |
| 56 | 36 | | if (BitConverter.IsLittleEndian) |
| 56 | 37 | | Array.Reverse(data); |
| | 38 | |
|
| | 39 | | // Write data |
| 56 | 40 | | bitWriter.WriteBits(data, Length * 5); |
| 56 | 41 | | } |
| | 42 | |
|
| | 43 | | /// <inheritdoc/> |
| | 44 | | public bool IsValid() |
| | 45 | | { |
| 196 | 46 | | return Value != uint256.Zero && Value != uint256.One; |
| | 47 | | } |
| | 48 | |
|
| | 49 | | /// <summary> |
| | 50 | | /// Reads a PaymentHashTaggedField from a BitReader |
| | 51 | | /// </summary> |
| | 52 | | /// <param name="bitReader">The BitReader to read from</param> |
| | 53 | | /// <param name="length">The length of the field</param> |
| | 54 | | /// <returns>The PaymentHashTaggedField</returns> |
| | 55 | | /// <exception cref="ArgumentException">Thrown when the length is invalid</exception> |
| | 56 | | internal static PaymentHashTaggedField FromBitReader(BitReader bitReader, short length) |
| | 57 | | { |
| 76 | 58 | | if (length != TaggedFieldConstants.HashLength) |
| 8 | 59 | | throw new ArgumentException( |
| 8 | 60 | | $"Invalid length for {nameof(PaymentHashTaggedField)}. Expected {TaggedFieldConstants.HashLength}, but g |
| | 61 | |
|
| | 62 | | // Read the data from the BitReader |
| 68 | 63 | | var data = new byte[(TaggedFieldConstants.HashLength * 5 + 7) / 8]; |
| 68 | 64 | | bitReader.ReadBits(data, length * 5); |
| 68 | 65 | | data = data[..^1]; |
| | 66 | |
|
| 68 | 67 | | if (BitConverter.IsLittleEndian) |
| 68 | 68 | | Array.Reverse(data); |
| | 69 | |
|
| 68 | 70 | | return new PaymentHashTaggedField(new uint256(data)); |
| | 71 | | } |
| | 72 | | } |