GetMinTxFee & use unsigned int for sizes.
[NovacoinLibrary.git] / Novacoin / VarInt.cs
index e78d107..ba174e9 100644 (file)
@@ -18,6 +18,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.IO;
 
 namespace Novacoin
 {
@@ -82,7 +83,7 @@ namespace Novacoin
             return EncodeVarInt((ulong)n);
         }
 
-        public static int GetEncodedSize(long n)
+        public static uint GetEncodedSize(long n)
         {
             if (n <= 0xfc)
             {
@@ -112,21 +113,42 @@ namespace Novacoin
         public static ulong DecodeVarInt(byte[] bytes)
         {
             var prefix = bytes[0];
-            var bytesArray = new byte[bytes.Length - 1];
 
-            bytes.CopyTo(bytesArray, 1);  // Get rid of prefix
+            if (bytes.Length > 1)
+            {
+                var bytesArray = new byte[bytes.Length - 1];
+                Array.Copy(bytes, 1, bytesArray, 0, bytesArray.Length);
+
+                switch (prefix)
+                {
+                    case 0xfd: // ushort flag
+                        return BitConverter.ToUInt16(bytesArray, 0);
+                    case 0xfe: // uint flag
+                        return BitConverter.ToUInt32(bytesArray, 0);
+                    case 0xff: // ulong flag
+                        return BitConverter.ToUInt64(bytesArray, 0);
+                }
+            }
+            
+            return prefix; // Values lower than 0xfd are stored directly
+        }
+
+        public static ulong ReadVarInt(ref BinaryReader reader)
+        {
+            byte prefix = reader.ReadByte();
 
             switch (prefix)
             {
-                case 0xfd: // ushort flag
-                    return BitConverter.ToUInt16(bytesArray, 0);
-                case 0xfe: // uint flag
-                    return BitConverter.ToUInt32(bytesArray, 0);
-                case 0xff: // ulong flag
-                    return BitConverter.ToUInt64(bytesArray, 0);
+                case 0xfd: // ushort
+                    return reader.ReadUInt16();
+                case 0xfe: // uint
+                    return reader.ReadUInt32();
+                case 0xff: // ulong
+                    return reader.ReadUInt64();
                 default:
                     return prefix;
             }
         }
+
     }
 }