Ejemplo n.º 1
0
 public static byte[] PreparePubKeyHashP2PKH(string publicAddress)
 {
     byte[] result        = Base58CheckEncoding.Decode(publicAddress);
     byte[] removedPrefix = new byte[result.Length - 1];
     Array.Copy(result, 1, removedPrefix, 0, removedPrefix.Length);
     return(removedPrefix);
 }
Ejemplo n.º 2
0
        public static PrivateKey FromWif(string base58)
        {
            var  data = Base58CheckEncoding.Decode(base58);
            bool compressed;

            var network = DigiByteNet.Network.GetFromPrivKeyPrefix(data[0]);

            if (network == null)
            {
                throw new ArgumentException("Invalid Network!");
            }

            if (data.Length == 1 + 32 + 1 && data[data.Length - 1] == 0x01)
            {
                compressed = true;
            }
            else if (data.Length == 1 + 32)
            {
                compressed = false;
            }
            else
            {
                throw new ArgumentException("Invalid WIF format!");
            }

            return(new PrivateKey(new BigInteger(data, 1, 32), compressed, network.Value));
        }
Ejemplo n.º 3
0
 public void DecodeBrokenBitcoinAddress()
 {
     Assert.Throws <FormatException>(() =>
     {
         Base58CheckEncoding.Decode(BROKEN_ADDRESS_TEXT);
     });
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Base58Check decoding.
        /// </summary>
        /// <param name="payload">The message to decode.</param>
        /// <param name="prefix">The prefix to truncate.</param>
        /// <returns>Base58 decoded message.</returns>
        public static byte[] Decode(string encoded, byte[] prefix = null)
        {
            int prefixLen = prefix?.Length ?? 0;

            byte[] msg = Base58CheckEncoding.Decode(encoded);

            byte[] result = new byte[msg.Length - prefixLen];

            Array.Copy(msg, prefixLen, result, 0, result.Length);

            return(result);
        }
Ejemplo n.º 5
0
        public void Encode_And_Decode_Hash()
        {
            var hash = HashHelper.ComputeFrom("hash");
            var data = hash.ToByteArray();

            var enCode = Base58CheckEncoding.Encode(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.Decode(enCode);

            deCode.ShouldBe(data);
        }
Ejemplo n.º 6
0
        public void Encode_And_Decode_Hash()
        {
            var hash = Hash.Generate();
            var data = hash.DumpByteArray();

            var enCode = Base58CheckEncoding.Encode(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.Decode(enCode);

            deCode.ShouldBe(data);
        }
Ejemplo n.º 7
0
        public static ChainAddress Parse(string chainAddressString, string symbol)
        {
            var arr = chainAddressString.Split('_');

            if (arr[0] != symbol)
            {
                throw new ArgumentException("invalid chain address", nameof(chainAddressString));
            }

            var address = Address.FromBase58(arr[1]);
            var chainId = Base58CheckEncoding.Decode(arr[2]).ToInt32(false);

            return(new ChainAddress(address, chainId));
        }
        public void Decode_Success()
        {
            ByteString data = new ByteString(Base58CheckEncoding.Decode("mzwhamFUz1oFz2noTGDK9dxq3PAEhNkpuL"));

            Assert.Equal(ByteString.Parse("6f" + "d5188210339b2012cd8f3c5ce3773d49dd7baa4b"), data);

            data = new ByteString(Base58CheckEncoding.Decode("mmvRqdAcJrSv6M8GozQE4tR3DhfF56c5M1"));
            Assert.Equal(ByteString.Parse("6f" + "4641508da141383ce2d1e035c58fad31480bcaac"), data);

            data = new ByteString(Base58CheckEncoding.Decode("n3GvU9Zo74UZLYgHQcYiLgTFcWfErXFdwe"));
            Assert.Equal(ByteString.Parse("6f" + "eeab6b6757f135e9ec2f47157c412f80493f1eca"), data);

            data = new ByteString(Base58CheckEncoding.Decode("1AaaBxiLVzo1xZSFpAw3Zm9YBYAYQgQuuU"));
            Assert.Equal(ByteString.Parse("00" + "691290451961ad74e177bf44f32d9e2fe7454ee6"), data);
        }
Ejemplo n.º 9
0
        public void Encode_And_Decode_Address()
        {
            var address = Address.Generate();
            var data    = address.DumpByteArray();

            var enCode = Base58CheckEncoding.Encode(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.Decode(enCode);

            deCode.ShouldBe(data);

            var deCode1 = Base58CheckEncoding.DecodePlain(enCode);

            deCode1.ShouldNotBe(data);
        }
Ejemplo n.º 10
0
        public void Encode_And_Decode_Address()
        {
            var address = Address.FromBase58("xFqJD9R33mQBQPr1hCFUZMayXFQ577j34MPyUdXzbPpAYufG2");
            var data    = address.ToByteArray();

            var enCode = Base58CheckEncoding.Encode(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.Decode(enCode);

            deCode.ShouldBe(data);

            var deCode1 = Base58CheckEncoding.DecodePlain(enCode);

            deCode1.ShouldNotBe(data);
        }
Ejemplo n.º 11
0
        public byte[] decode(string data)
        {
            // Not valid if it doesn't have head/foot
            if (!data.Contains(head) | !data.Contains(foot))
            {
                throw new InvalidSimplePackHeader();
            }
            string base58Data = "";

            // Extract the encoded part without header/footer
            for (int i = head.Length; i < data.Length - foot.Length; i++)
            {
                base58Data += data[i];
            }
            // Will raise System.FormatException if checksum is not valid (or invalid footer/header)
            return(Base58CheckEncoding.Decode(base58Data));
        }
Ejemplo n.º 12
0
        public static Address FromString(string address)
        {
            var data = Base58CheckEncoding.Decode(address);

            if (data.Length != 20 + 1)
            {
                throw new ArgumentException("Invalid address");
            }

            var network = Network.GetFromPubKeyHash(data[0]);

            if (network == null)
            {
                throw new ArgumentException("Unknown address hash");
            }

            return(new Address(data.Skip(1).Take(20).ToArray(), network.Value));
        }
Ejemplo n.º 13
0
        public void EncodePlain_And_DecodePlain_Hash()
        {
            var hash  = HashHelper.ComputeFrom("hash");
            var data  = hash.ToByteArray();
            var bytes = new byte[] { 0 };

            var enCode = Base58CheckEncoding.EncodePlain(data);

            enCode.ShouldNotBe(string.Empty);
            var deCode = Base58CheckEncoding.DecodePlain(enCode);

            deCode.ShouldBe(data);

            Base58CheckEncoding.EncodePlain(bytes).ShouldBe("1");
            Should.Throw <FormatException>(() => {
                Base58CheckEncoding.DecodePlain(bytes.ToString());
            });

            Should.Throw <FormatException>(() => { Base58CheckEncoding.Decode(enCode); });
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Method to check whether an address is vald base58
        /// </summary>
        /// <param name="addressString"></param>
        /// <returns>bool value if or not address is base58</returns>
        private bool ValidBase58(string addressString)
        {
            bool isValidbase58address = false;

            if (String.IsNullOrWhiteSpace(addressString))
            {
                return(false);
            }

            try
            {
                Base58CheckEncoding.Decode(addressString);
                isValidbase58address = true;
            }
            catch (Exception ex)
            {
                isValidbase58address = false;
            }

            return(isValidbase58address);
        }
 public PublicIdentityKey(string keyString)
 {
     if (keyString == null)
     {
         throw new System.ArgumentException("Parameter cannot be null", "keyString");
     }
     else if (keyString.Length != 55 || keyString.Substring(0, 5) != "idpub")
     {
         throw new System.ArgumentException("Invalid public key string", "keyString");
     }
     byte[] withPrefix;
     try
     {
         withPrefix = Base58CheckEncoding.Decode(keyString);
     }
     catch (FormatException)
     {
         throw new System.ArgumentException("Invalid public key string", "keyString");
     }
     Bytes = new byte[KEY_LENGTH];
     System.Buffer.BlockCopy(withPrefix, PublicIdentityKey.PREFIX.Length, Bytes, 0, Bytes.Length);
 }
Ejemplo n.º 16
0
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            txtDecriptado.Text = "";
            this.Refresh();
            String startString = txtEncriptado.Text;
            UInt16 blockCnt    = 0;
            String finalString = "";

            foreach (string cryptBlock in startString.Split('_'))
            {
                byte[] cryptArr;
                try
                {
                    cryptArr = Base58CheckEncoding.Decode(cryptBlock);
                }
                catch
                {
                    return;
                }

                BigInteger criptado          = new BigInteger(cryptArr);
                BigInteger decriptado        = BigInteger.ModPow(criptado, privateExp, n);
                byte[]     decryptWithPadArr = decriptado.ToByteArray();
                byte[]     decryptArr        = new byte[decryptWithPadArr.Length - 4];
                Array.Copy(decryptWithPadArr, decryptArr, decryptArr.Length);
                Array.Reverse(decryptArr);
                String rsaDec = Encoding.UTF8.GetString(decryptArr);
                finalString += rsaDec;
                blockCnt++;
            }

            txtDecriptado.Text = finalString;
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;
        }
Ejemplo n.º 17
0
        /// <summary>
        ///     Decode a CurveLock ID into a byte array.
        /// </summary>
        /// <param name="encodedPublicKey">The CurveLock ID.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="CorruptIdentityException"></exception>
        /// <returns>A 32 byte array.</returns>
        public static byte[] DecodeCurveLockPublicKey(string encodedPublicKey)
        {
            if (encodedPublicKey == null)
            {
                throw new ArgumentNullException("encodedPublicKey", "encodedPublicKey cannot be null");
            }

            try
            {
                var raw     = Base58CheckEncoding.Decode(encodedPublicKey);
                var version = ArrayHelper.SubArray(raw, 0, 1);
                if (!version.SequenceEqual(new[] { CurveLockVersionPrefix }))
                {
                    throw new FormatException("invalid version");
                }

                var publicKey = ArrayHelper.SubArray(raw, 1);
                return(publicKey);
            }
            catch (FormatException)
            {
                throw new CorruptIdentityException("the given identity seems to be an invalid CurveLock ID");
            }
        }
Ejemplo n.º 18
0
        public Key FromWif(string PrivKey)
        {
            byte[] ExtendedKeyBytes = Base58CheckEncoding.Decode(PrivKey);
            bool   Compressed       = false;

            //skip the version byte
            ExtendedKeyBytes = ExtendedKeyBytes.Skip(1).ToArray();
            if (ExtendedKeyBytes.Length == 33)
            {
                if (ExtendedKeyBytes[32] != 0x01)
                {
                    throw new ArgumentException("Invalid compression flag", "PrivKey");
                }
                ExtendedKeyBytes = ExtendedKeyBytes.Take(ExtendedKeyBytes.Count() - 1).ToArray();
                Compressed       = true;
            }

            if (ExtendedKeyBytes.Length != 32)
            {
                throw new ArgumentException("Invalid WIF payload length", "PrivKey");
            }

            return(new Key(ExtendedKeyBytes, -1, Compressed));
        }
Ejemplo n.º 19
0
        public void DecodeBrokenBitcoinAddress()
        {
            var actualBytes = Base58CheckEncoding.Decode(BROKEN_ADDRESS_TEXT);

            Assert.AreEqual(BitConverter.ToString(AddressBytes), BitConverter.ToString(actualBytes));
        }
Ejemplo n.º 20
0
        // ---

        protected async Task <string[]> callContractConstantMethod(string contractAddress, string methodSelector, string[] paramsHex)
        {
            var addressHex = (string)null;

            try {
                Hex.Decode(contractAddress);
                addressHex = contractAddress;
            }
            catch {
                try {
                    addressHex = Hex.ToHexString(Base58CheckEncoding.Decode(contractAddress));
                }
                catch {
                    throw new ArgumentException("Invalid contract address");
                }
            }

            var parameter = (string)null;

            if (paramsHex != null && paramsHex.Length > 0)
            {
                parameter = paramsHex.Join("");
            }

            var body = new {
                contract_address  = addressHex,
                function_selector = methodSelector,
                parameter         = parameter,
            };

            var result = new ContractConstantMethodResult()
            {
                ConstantResult = null,
                Result         = new ContractConstantMethodResult.ResultData()
                {
                    Result = false,
                }
            };

            using (var req = new Request(Logger)) {
                await req
                .AcceptJson()
                .BodyJson(body)
                .OnResult(async(res) => {
                    if (res.GetHttpStatus() == null || res.GetHttpStatus().Value != HttpStatusCode.OK)
                    {
                        throw new Exception("Invalid HTTP status");
                    }
                    var raw = await res.ToRawString();
                    if (!Json.ParseInto(raw, result, Json.SnakeCaseSettings))
                    {
                        throw new Exception("Failed to parse");
                    }
                })
                .SendPost(string.Concat(API.TrimEnd('/'), "/wallet/triggersmartcontract"))
                ;
            }

            if (!(result?.Result?.Result ?? false) || (result?.ConstantResult?.Length ?? 0) == 0)
            {
                throw new Exception("Invalid result");
            }

            return(result.ConstantResult);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Construct address from base58 encoded string.
 /// </summary>
 /// <param name="inputStr"></param>
 /// <returns></returns>
 public static Address FromBase58(string inputStr)
 {
     return(FromBytes(Base58CheckEncoding.Decode(inputStr)));
 }