| | 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 minimum final cltv expiry |
| | 11 | | /// </summary> |
| | 12 | | /// <remarks> |
| | 13 | | /// The minimum final cltv expiry is a 4 byte field that specifies the minimum number of blocks that the receiver should |
| | 14 | | /// </remarks> |
| | 15 | | /// <seealso cref="ITaggedField"/> |
| | 16 | | internal sealed class MinFinalCltvExpiryTaggedField : ITaggedField |
| | 17 | | { |
| 136 | 18 | | public TaggedFieldTypes Type => TaggedFieldTypes.MIN_FINAL_CLTV_EXPIRY; |
| 100 | 19 | | internal ushort Value { get; } |
| 72 | 20 | | public short Length { get; } |
| | 21 | |
|
| | 22 | | /// <summary> |
| | 23 | | /// Initializes a new instance of the <see cref="MinFinalCltvExpiryTaggedField"/> class. |
| | 24 | | /// </summary> |
| | 25 | | /// <param name="value">The Expiry Time in seconds</param> |
| 48 | 26 | | internal MinFinalCltvExpiryTaggedField(ushort value) |
| | 27 | | { |
| 48 | 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 |
| 48 | 31 | | Length = (short)((BitOperations.Log2(Value) + 1 + 4) / 5); |
| 48 | 32 | | } |
| | 33 | |
|
| | 34 | | /// <inheritdoc/> |
| | 35 | | public void WriteToBitWriter(BitWriter bitWriter) |
| | 36 | | { |
| | 37 | | // Write data |
| 24 | 38 | | bitWriter.WriteUInt16AsBits(Value, Length * 5); |
| 24 | 39 | | } |
| | 40 | |
|
| | 41 | | /// <inheritdoc/> |
| | 42 | | public bool IsValid() |
| | 43 | | { |
| 4 | 44 | | return Value > 0; |
| | 45 | | } |
| | 46 | |
|
| | 47 | | /// <summary> |
| | 48 | | /// Reads a MinFinalCltvExpiryTaggedField 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 MinFinalCltvExpiryTaggedField</returns> |
| | 53 | | /// <exception cref="ArgumentException">Thrown when the length is invalid</exception> |
| | 54 | | internal static MinFinalCltvExpiryTaggedField FromBitReader(BitReader bitReader, short length) |
| | 55 | | { |
| 4 | 56 | | if (length <= 0) |
| | 57 | | { |
| 0 | 58 | | throw new ArgumentException("Invalid length for MinFinalCltvExpiryTaggedField. Length must be greater than 0 |
| | 59 | | } |
| | 60 | |
|
| | 61 | | // Read the data from the BitReader |
| 4 | 62 | | var value = bitReader.ReadUInt16FromBits(length * 5); |
| | 63 | |
|
| 4 | 64 | | return new MinFinalCltvExpiryTaggedField(value); |
| | 65 | | } |
| | 66 | | } |