| | 1 | | using System.Numerics; |
| | 2 | |
|
| | 3 | | namespace NLightning.Bolt11.Models.TaggedFields; |
| | 4 | |
|
| | 5 | | using Common.Utils; |
| | 6 | | using Enums; |
| | 7 | | using Interfaces; |
| | 8 | |
|
| | 9 | | /// <summary> |
| | 10 | | /// Tagged field for the expiry time |
| | 11 | | /// </summary> |
| | 12 | | /// <remarks> |
| | 13 | | /// The expiry time is the time in seconds after which the invoice is invalid. |
| | 14 | | /// </remarks> |
| | 15 | | /// <seealso cref="ITaggedField"/> |
| | 16 | | public sealed class ExpiryTimeTaggedField : ITaggedField |
| | 17 | | { |
| 320 | 18 | | public TaggedFieldTypes Type => TaggedFieldTypes.EXPIRY_TIME; |
| 212 | 19 | | internal int Value { get; } |
| 96 | 20 | | public short Length { get; } |
| | 21 | |
|
| | 22 | | /// <summary> |
| | 23 | | /// Initializes a new instance of the <see cref="ExpiryTimeTaggedField"/> class. |
| | 24 | | /// </summary> |
| | 25 | | /// <param name="value">The Expiry Time in seconds</param> |
| 100 | 26 | | internal ExpiryTimeTaggedField(int value) |
| | 27 | | { |
| 100 | 28 | | Value = value; |
| | 29 | | // Calculate the length of the field by getting the number of bits needed to represent the value plus 1 |
| | 30 | | // then add 4 to round up to the next multiple of 5 and divide by 5 to get the number of bytes |
| 100 | 31 | | Length = (short)((BitOperations.Log2((uint)Value) + 1 + 4) / 5); |
| 100 | 32 | | } |
| | 33 | |
|
| | 34 | | /// <inheritdoc/> |
| | 35 | | public void WriteToBitWriter(BitWriter bitWriter) |
| | 36 | | { |
| | 37 | | // Write data |
| 32 | 38 | | bitWriter.WriteInt32AsBits(Value, Length * 5); |
| 32 | 39 | | } |
| | 40 | |
|
| | 41 | | /// <inheritdoc/> |
| | 42 | | public bool IsValid() |
| | 43 | | { |
| 24 | 44 | | return Value > 0; |
| | 45 | | } |
| | 46 | |
|
| | 47 | | /// <summary> |
| | 48 | | /// Reads a ExpiryTimeTaggedField from a BitReader |
| | 49 | | /// </summary> |
| | 50 | | /// <param name="bitReader">The BitReader to read from</param> |
| | 51 | | /// <param name="length">The length of the field</param> |
| | 52 | | /// <returns>The ExpiryTimeTaggedField</returns> |
| | 53 | | /// <exception cref="ArgumentException">Thrown when the length is invalid</exception> |
| | 54 | | internal static ExpiryTimeTaggedField FromBitReader(BitReader bitReader, short length) |
| | 55 | | { |
| 40 | 56 | | if (length <= 0) |
| | 57 | | { |
| 4 | 58 | | throw new ArgumentException("Invalid length for ExpiryTimeTaggedField. Length must be greater than 0", nameo |
| | 59 | | } |
| | 60 | |
|
| | 61 | | // Read the data from the BitReader |
| 36 | 62 | | var value = bitReader.ReadInt32FromBits(length * 5); |
| | 63 | |
|
| 36 | 64 | | return new ExpiryTimeTaggedField(value); |
| | 65 | | } |
| | 66 | | } |