| | 1 | | namespace NLightning.Bolt11.Models.TaggedFields; |
| | 2 | |
|
| | 3 | | using Common.Utils; |
| | 4 | | using Enums; |
| | 5 | | using Interfaces; |
| | 6 | |
|
| | 7 | | /// <summary> |
| | 8 | | /// Tagged field for the metadata |
| | 9 | | /// </summary> |
| | 10 | | /// <remarks> |
| | 11 | | /// The metadata is a variable length field that can be used to store additional information |
| | 12 | | /// </remarks> |
| | 13 | | /// <seealso cref="ITaggedField"/> |
| | 14 | | internal sealed class MetadataTaggedField : ITaggedField |
| | 15 | | { |
| 96 | 16 | | public TaggedFieldTypes Type => TaggedFieldTypes.METADATA; |
| 88 | 17 | | internal byte[] Value { get; } |
| 72 | 18 | | public short Length { get; } |
| | 19 | |
|
| | 20 | | /// <summary> |
| | 21 | | /// Initializes a new instance of the <see cref="MetadataTaggedField"/> class. |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="value">The metadata bytes</param> |
| 88 | 24 | | internal MetadataTaggedField(byte[] value) |
| | 25 | | { |
| 88 | 26 | | Value = value; |
| 88 | 27 | | Length = (short)Math.Ceiling(value.Length * 8 / 5.0); |
| 88 | 28 | | } |
| | 29 | |
|
| | 30 | | /// <inheritdoc/> |
| | 31 | | public void WriteToBitWriter(BitWriter bitWriter) |
| | 32 | | { |
| | 33 | | // Write data |
| 24 | 34 | | bitWriter.WriteBits(Value, Length * 5); |
| 24 | 35 | | } |
| | 36 | |
|
| | 37 | | /// <inheritdoc/> |
| | 38 | | public bool IsValid() |
| | 39 | | { |
| 4 | 40 | | return true; |
| | 41 | | } |
| | 42 | |
|
| | 43 | | /// <summary> |
| | 44 | | /// Reads a MetadataTaggedField from a BitReader |
| | 45 | | /// </summary> |
| | 46 | | /// <param name="bitReader">The BitReader to read from</param> |
| | 47 | | /// <param name="length">The length of the field</param> |
| | 48 | | /// <returns>The MetadataTaggedField</returns> |
| | 49 | | /// <exception cref="ArgumentException">Thrown when the length is invalid</exception> |
| | 50 | | internal static MetadataTaggedField FromBitReader(BitReader bitReader, short length) |
| | 51 | | { |
| 52 | 52 | | if (length <= 0) |
| | 53 | | { |
| 8 | 54 | | throw new ArgumentException("Invalid length for MetadataTaggedField. Length must be greater than 0", nameof( |
| | 55 | | } |
| | 56 | |
|
| | 57 | | // Read the data from the BitReader |
| 44 | 58 | | var data = new byte[(length * 5 + 7) / 8]; |
| 44 | 59 | | bitReader.ReadBits(data, length * 5); |
| | 60 | |
|
| 44 | 61 | | return new MetadataTaggedField(length * 5 % 8 > 0 ? data[..^1] : data); |
| | 62 | | } |
| | 63 | | } |