2 * Novacoin classes library
3 * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 using System.Collections.Generic;
28 /// Encodes unsigned integer value into compact representation.
30 /// See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for additional information.
32 /// <param name="n">Unsigned integer value</param>
33 /// <returns>Byte sequence</returns>
34 public static byte[] EncodeVarInt(ulong n)
36 var resultBytes = new List<byte>();
40 // Values up to 0xfc are stored directly without any prefix
41 resultBytes.Add((byte)n);
48 if (n <= ushort.MaxValue)
52 valueBytes = BitConverter.GetBytes((ushort)n);
54 else if (n <= uint.MaxValue)
58 valueBytes = BitConverter.GetBytes((uint)n);
64 valueBytes = BitConverter.GetBytes(n);
67 resultBytes.Add(prefix);
68 resultBytes.AddRange(valueBytes);
71 return resultBytes.ToArray();
75 /// Encodes integer value into compact representation.
77 /// See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for additional information.
79 /// <param name="n">Integer value</param>
80 /// <returns>Byte sequence</returns>
81 public static byte[] EncodeVarInt(long n)
83 return EncodeVarInt((ulong)n);
86 public static int GetEncodedSize(long n)
92 else if (n <= ushort.MaxValue)
96 else if (n <= uint.MaxValue)
107 /// Decodes integer value from compact representation
109 /// See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for additional information.
111 /// <param name="bytes">Byte sequence</param>
112 /// <returns>Integer value</returns>
113 public static ulong DecodeVarInt(byte[] bytes)
115 var prefix = bytes[0];
116 var bytesArray = new byte[bytes.Length - 1];
118 bytes.CopyTo(bytesArray, 1); // Get rid of prefix
122 case 0xfd: // ushort flag
123 return BitConverter.ToUInt16(bytesArray, 0);
124 case 0xfe: // uint flag
125 return BitConverter.ToUInt32(bytesArray, 0);
126 case 0xff: // ulong flag
127 return BitConverter.ToUInt64(bytesArray, 0);
133 public static ulong ReadVarInt(ref BinaryReader reader)
135 byte prefix = reader.ReadByte();
140 return reader.ReadUInt16();
142 return reader.ReadUInt32();
144 return reader.ReadUInt64();