Example #1
0
        private static byte[] DecodeDataCore(string encoded)
        {
            var result = new byte[0];

            if (encoded.Length == 0)
            {
                return(result);
            }
            BigInteger bn58 = 58;
            BigInteger bn   = 0;
            BigInteger bnChar;
            int        i = 0;

            while (DataEncoder.IsSpace(encoded[i]))
            {
                i++;
                if (i >= encoded.Length)
                {
                    return(result);
                }
            }

            for (int y = i; y < encoded.Length; y++)
            {
                var p1 = pszBase58.IndexOf(encoded[y]);
                if (p1 == -1)
                {
                    while (DataEncoder.IsSpace(encoded[y]))
                    {
                        y++;
                        if (y >= encoded.Length)
                        {
                            break;
                        }
                    }
                    if (y != encoded.Length)
                    {
                        throw new FormatException("Invalid base 58 string");
                    }
                    break;
                }
                bnChar = new BigInteger(p1);
                bn     = BigInteger.Multiply(bn, bn58);
                bn    += bnChar;
            }

            // Get bignum as little endian data
            var vchTmp = bn.ToByteArray();

            if (vchTmp.All(b => b == 0))
            {
                vchTmp = new byte[0];
            }

            // Trim off sign byte if present
            if (vchTmp.Length >= 2 && vchTmp[vchTmp.Length - 1] == 0 && vchTmp[vchTmp.Length - 2] >= 0x80)
            {
                vchTmp = vchTmp.Take(vchTmp.Length - 1).ToArray();
            }

            // Restore leading zeros
            int nLeadingZeros = 0;

            for (int y = i; y < encoded.Length && encoded[y] == pszBase58[0]; y++)
            {
                nLeadingZeros++;
            }


            result = new byte[nLeadingZeros + vchTmp.Length];
            Array.Copy(vchTmp.Reverse().ToArray(), 0, result, nLeadingZeros, vchTmp.Length);
            return(result);
        }