Correct checksum computation
[NovacoinLibrary.git] / Novacoin / AddressTools.cs
1 \feffusing System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 using System.Numerics;
8
9 namespace Novacoin
10 {
11     public class AddressTools
12     {
13         public static string Base58Encode(byte[] bytes)
14         {
15             const string strDigits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
16             string strResult = "";
17
18             int nBytes = bytes.Length;
19             BigInteger arrayToInt = 0;
20             BigInteger encodeSize = strDigits.Length;
21
22             for (int i = 0; i < nBytes; ++i)
23             {
24                 arrayToInt = arrayToInt * 256 + bytes[i];
25             }
26             while (arrayToInt > 0)
27             {
28                 int rem = (int)(arrayToInt % encodeSize);
29                 arrayToInt /= encodeSize;
30                 strResult = strDigits[rem] + strResult;
31             }
32             for (int i = 0; i < nBytes && bytes[i] == 0; ++i)
33             {
34                 strResult = strDigits[0] + strResult;
35             }
36
37             return strResult;
38         }
39
40         public static string Base58EncodeCheck(byte[] bytes)
41         {
42             byte[] dataBytes = new byte[bytes.Length + 4];
43             byte[] checkSum = Hash256.Compute256(bytes).hashBytes.Take(4).ToArray();
44
45             bytes.CopyTo(dataBytes, 0);
46             checkSum.CopyTo(dataBytes, bytes.Length);
47
48             return Base58Encode(dataBytes);
49         }
50     }
51 }