public string ToAddressString(string addressPrefix = null)
        {
            if (addressPrefix.IsNull())
            {
                addressPrefix = ChainConfig.AddressPrefix;
            }
            var buffer = ToBuffer(true);
            var hash   = SHA512.Create().HashAndDispose(buffer);

            buffer.Clear();
            var firstChecksum = RIPEMD160.Create().HashAndDispose(hash);

            hash.Clear();
            var secondChecksum = RIPEMD160.Create().HashAndDispose(firstChecksum);
            var checksum       = secondChecksum.Slice(0, 4);

            secondChecksum.Clear();
            buffer = firstChecksum.Concat(checksum);
            firstChecksum.Clear();
            checksum.Clear();
            var result = addressPrefix + Base58CheckEncoding.EncodePlain(buffer);

            buffer.Clear();
            return(result);
        }
        public string ToPtsAddy()
        {
            var buffer    = ToBuffer(true);
            var firstHash = SHA256.Create().HashAndDispose(buffer);

            buffer.Clear();
            var secondHash = RIPEMD160.Create().HashAndDispose(firstHash);

            firstHash.Clear();
            var hash = new byte[] { 0x38 }.Concat(secondHash); // version 56(decimal)

            secondHash.Clear();
            var firstChecksum  = SHA256.Create().HashAndDispose(hash);
            var secondChecksum = SHA256.Create().HashAndDispose(firstChecksum);

            firstChecksum.Clear();
            var checksum = secondChecksum.Slice(0, 4);

            secondChecksum.Clear();
            buffer = hash.Concat(checksum);
            checksum.Clear();
            hash.Clear();
            var result = Base58CheckEncoding.EncodePlain(buffer);

            buffer.Clear();
            return(result);
        }
 public static IPublicKey FromPublicKeyString(string publicKey, string addressPrefix = null)
 {
     try
     {
         if (addressPrefix.IsNull())
         {
             addressPrefix = ChainConfig.AddressPrefix;
         }
         var prefix = publicKey.Substring(0, addressPrefix.Length);
         Assert.Equal(
             addressPrefix, prefix,
             string.Format("Expecting key to begin with {0}, instead got {1}", addressPrefix, prefix)
             );
         publicKey = publicKey.Substring(addressPrefix.Length);
         var key      = Base58CheckEncoding.DecodePlain(publicKey);
         var checksum = key.Slice(key.Length - 4);
         var buffer   = key.Slice(0, key.Length - 4);
         key.Clear();
         var hash        = RIPEMD160.Create().HashAndDispose(buffer);
         var newChecksum = hash.Slice(0, 4);
         hash.Clear();
         if (!checksum.DeepEqual(newChecksum))
         {
             throw new InvalidOperationException("Checksum did not match");
         }
         var result = FromBuffer(buffer);
         buffer.Clear();
         return(result);
     }
     catch
     {
         return(null);
     }
 }
Exemple #4
0
        public static void Do2()
        {
            var lengths = new Dictionary <int, List <string> >();

            for (var i = 0; i < 100; i++)
            {
                var b = ByteUtils.RandomBytes(4);
                Console.WriteLine(BitConverter.ToString(b).Replace("-", string.Empty));

                var byteString = Base58CheckEncoding.EncodePlain(b);
                var length     = byteString.Length;

                // Console.WriteLine(byteString);
                if (lengths.ContainsKey(length))
                {
                    lengths[length].Append(byteString);
                }
                else
                {
                    lengths.Add(length, new List <string> {
                        byteString
                    });
                }
            }

            foreach (var v in lengths.Keys)
            {
                Console.WriteLine($"{v}: {lengths[v][0]}");
            }

            foreach (var length in lengths)
            {
                Console.WriteLine($"Kvp - [length, occurrences] {length}.");
            }
        }
Exemple #5
0
        public static void Do()
        {
            for (var i = 0; i < 100; i++)
            {
                BigInteger randomBigInt    = i;
                var        randomBytes     = new byte[] { 0x00, 0x00, 0x00, 0x00 };
                var        bigIntByteArray = randomBigInt.ToByteArray();
                if (bigIntByteArray.Length == 1)
                {
                    randomBytes[3] = bigIntByteArray[0];
                }

                if (bigIntByteArray.Length == 2)
                {
                    randomBytes[3] = bigIntByteArray[0];
                    randomBytes[2] = bigIntByteArray[1];
                }

                if (bigIntByteArray.Length == 3)
                {
                    randomBytes[3] = bigIntByteArray[0];
                    randomBytes[2] = bigIntByteArray[1];
                    randomBytes[1] = bigIntByteArray[2];
                }

                var base58String = Base58CheckEncoding.EncodePlain(randomBytes);
                Console.WriteLine($"Bytes: {string.Concat(randomBytes.Select(b => b.ToString("X2")))} Byte length: {bigIntByteArray.Length}, {base58String}");
            }
        }
Exemple #6
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));
        }
 public void DecodeInvalidChar()
 {
     Assert.Throws <FormatException>(() =>
     {
         Base58CheckEncoding.DecodePlain("ab0");
     });
 }
Exemple #8
0
        public static string Sha1(byte[] data)
        {
            var hash   = SHA1.Create().ComputeHash(data);
            var result = Base58CheckEncoding.Encode(hash);

            return(result);
        }
Exemple #9
0
        /// <inheritdoc/>
        public async Task <byte[]> DownloadBytesAsync(byte[] address)
        {
            if (downloadClient != null)
            {
                byte[] bytes = new byte[digestSize + 2];
                bytes[0] = fnCode;
                bytes[1] = digestSize;
                address.CopyTo(bytes, 2);
                //Encoding.Unicode.GetBytes(address, 0, address.Length, bytes, 2);

                string      hash            = Base58CheckEncoding.EncodePlain(bytes);
                RestRequest downloadRequest = new RestRequest("/ipfs/" + hash, Method.GET);
                downloadRequest.AddDecompressionMethod(System.Net.DecompressionMethods.None);

                IRestResponse response = await downloadClient.ExecuteGetTaskAsync(downloadRequest);

                if (response.ErrorException != null)
                {
                    // TODO: throw some kind of custom exception on unsuccessful upload
                    throw new Exception();
                }

                return(response.RawBytes);
            }
            return(null);
        }
Exemple #10
0
        public async Task TestCreateKeyWorksForSeed()
        {
            var paramJson = string.Format("{{\"seed\":\"{0}\"}}", MY1_SEED);
            var senderVk  = await Crypto.CreateKeyAsync(wallet, paramJson);

            Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(senderVk).Length);
        }
Exemple #11
0
        /// <summary>
        ///     Decode a bytejail ID into a byte array.
        /// </summary>
        /// <param name="encodedPublicKey">The bytejail ID.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="CorruptIdentityException"></exception>
        /// <returns>A 32 byte array.</returns>
        public static byte[] DecodeBytejailPublicKey(string encodedPublicKey)
        {
            if (encodedPublicKey == null)
            {
                throw new ArgumentNullException("encodedPublicKey", "encodedPublicKey cannot be null");
            }

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

                var publicKey     = ArrayHelper.SubArray(raw, 1, 32);
                var checksum      = CalculateBytejailChecksum(new[] { BytejailVersionPrefix }, publicKey);
                var givenChecksum = ArrayHelper.SubArray(raw, 33);
                if (!checksum.SequenceEqual(givenChecksum))
                {
                    throw new CorruptIdentityException("the given identity seems to be an invalid bytejail ID");
                }

                return(publicKey);
            }
            catch (FormatException)
            {
                throw new CorruptIdentityException("the given identity seems to be an invalid bytejail ID");
            }
        }
Exemple #12
0
            public API_History_4_3(SealedTransaction T)
            {
                id           = ConvertTransactionId(T.Id);
                source       = Base58CheckEncoding.EncodePlain(T.Trxn.Source);
                target       = Base58CheckEncoding.EncodePlain(T.Trxn.Target);
                amount       = BcToDouble(T.Trxn.Amount);
                fee          = BcFeeConvert(T.Trxn.Fee.Commission);
                timeCreation = new DateTime(T.Trxn.TimeCreation);
                userFields   = T.Trxn.UserFields;
                type         = (API_TransactionType)T.Trxn.Type;

                if (T.Trxn.ExtraFee != null)
                {
                    extraFee = T.Trxn.ExtraFee.Select(m => (API_ExtraFee) new API_ExtraFee_4_3(m)).ToList();
                }

                if (T.Trxn.SmartContract != null)
                {
                    smartContract = new API_SmartContract_4_3(T.Trxn.SmartContract);
                }

                if (T.Trxn.SmartInfo != null)
                {
                    smartInfo = new API_SmartTransInfo_4_3(T.Trxn.SmartInfo);
                }
            }
 override public string ToString()
 {
     byte[] keyBody = new byte[PublicIdentityKey.PREFIX.Length + Bytes.Length];
     System.Buffer.BlockCopy(PublicIdentityKey.PREFIX, 0, keyBody, 0, PublicIdentityKey.PREFIX.Length);
     System.Buffer.BlockCopy(Bytes, 0, keyBody, PublicIdentityKey.PREFIX.Length, Bytes.Length);
     return(Base58CheckEncoding.Encode(keyBody));
 }
        public async Task TestReplaceKeysStartWorksForEmptyJson()
        {
            var result = await Signus.ReplaceKeysStartAsync(wallet, _did, "{}");

            Assert.IsNotNull(result);
            Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(result).Length);
        }
Exemple #15
0
        /// <summary>
        ///     Try to recognize the identity format.
        /// </summary>
        /// <param name="encodedPublicKey">A base58 encoded public identity.</param>
        /// <param name="validate">If true, the key will also be validated.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>The KeyType.</returns>
        public static KeyType TryRecognizeIdentityFormat(string encodedPublicKey, bool validate = true)
        {
            var type = KeyType.Unknown;

            if (encodedPublicKey == null)
            {
                throw new ArgumentNullException("encodedPublicKey", "encodedPublicKey cannot be null");
            }

            try
            {
                var raw = Base58CheckEncoding.DecodePlain(encodedPublicKey);

                switch (raw.Length)
                {
                case 33:
                    // miniLock
                    type = validate
                            ? (DecodeMiniLockPublicKey(encodedPublicKey).Length == PublicKeyBytes
                                ? KeyType.MiniLock
                                : KeyType.Invalid)
                            : KeyType.MiniLock;
                    break;

                case 37:
                    // curvelock or bytejail
                    if (ArrayHelper.SubArray(raw, 0, 1).SequenceEqual(new[] { CurveLockVersionPrefix }))
                    {
                        // CurveLock
                        type = validate
                                ? (DecodeCurveLockPublicKey(encodedPublicKey).Length == PublicKeyBytes
                                    ? KeyType.CurveLock
                                    : KeyType.Invalid)
                                : KeyType.CurveLock;
                    }
                    else
                    {
                        if (ArrayHelper.SubArray(raw, 0, 1).SequenceEqual(new[] { BytejailVersionPrefix }))
                        {
                            // bytejail
                            type = validate
                                    ? (DecodeBytejailPublicKey(encodedPublicKey).Length == PublicKeyBytes
                                        ? KeyType.Bytejail
                                        : KeyType.Invalid)
                                    : KeyType.Bytejail;
                        }
                    }
                    break;

                default:
                    type = KeyType.Unknown;
                    break;
                }
            }
            catch (Exception)
            {
                type = KeyType.Invalid;
            }
            return(type);
        }
Exemple #16
0
        public static IPrivateKey FromWif(string wif)
        {
            var fullBuffer = Base58CheckEncoding.DecodePlain(wif);

            Assert.Equal(0x80, fullBuffer.First(), string.Format("Expected version {0}, instead got {1}", 0x80, fullBuffer.First()));
            var buffer   = fullBuffer.Slice(0, fullBuffer.Length - 4);
            var checksum = fullBuffer.Slice(fullBuffer.Length - 4);

            fullBuffer.Clear();
            var firstChecksum  = SHA256.Create().HashAndDispose(buffer);
            var secondChecksum = SHA256.Create().HashAndDispose(firstChecksum);

            firstChecksum.Clear();
            var newChecksum = secondChecksum.Slice(0, 4);

            secondChecksum.Clear();
            if (!checksum.DeepEqual(newChecksum))
            {
                throw new InvalidOperationException("Checksum did not match");
            }
            checksum.Clear();
            newChecksum.Clear();
            var key = buffer.Slice(1, 32);

            buffer.Clear();
            var result = FromBuffer(key);

            key.Clear();
            return(result);
        }
 public void DecodeBrokenBitcoinAddress()
 {
     Assert.Throws <FormatException>(() =>
     {
         Base58CheckEncoding.Decode(BROKEN_ADDRESS_TEXT);
     });
 }
 override public string ToString()
 {
     byte[] withPrefix = new byte[PrivateIdentityKey.PREFIX.Length + Seed.Length];
     System.Buffer.BlockCopy(PrivateIdentityKey.PREFIX, 0, withPrefix, 0, PrivateIdentityKey.PREFIX.Length);
     System.Buffer.BlockCopy(Seed, 0, withPrefix, PrivateIdentityKey.PREFIX.Length, Seed.Length);
     return(Base58CheckEncoding.Encode(withPrefix));
 }
Exemple #19
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);
 }
Exemple #20
0
 public ActionResult UnsafeTransaction(TransactionCreateModel model)
 {
     if (model.Priv == null)
     {
         return(Json(_api.Api.SendTransaction(new CreateTransactionModel(model))));
     }
     else
     {
         byte[] Private;
         try
         {
             Private = Base58CheckEncoding.DecodePlain(model.Priv);
         }
         catch (Exception ex)
         {
             Response.StatusCode = (int)HttpStatusCode.Forbidden;
             return(Json(ex.Message, JsonRequestBehavior.AllowGet));
         }
         try
         {
             return(Json(_api.Api.SendTransaction(new CreateTransactionModel(model), Private)));
         }
         catch (Exception ex)
         {
             Response.StatusCode = (int)HttpStatusCode.Forbidden;
             return(Json(ex.Message, JsonRequestBehavior.AllowGet));
         }
     }
 }
Exemple #21
0
 public static bool VerifyFormattedAddress(string formattedAddress)
 {
     if (string.IsNullOrEmpty(formattedAddress))
     {
         return(false);
     }
     return(Base58CheckEncoding.Verify(formattedAddress));
 }
Exemple #22
0
        /// <summary>
        /// Calculates Bitcoin P2PKH address given public key hash and network version bytes
        /// </summary>
        /// <param name="hash">public key hash</param>
        /// <param name="versionBytes">version bytes of network</param>
        /// <returns>base58check address</returns>
        public static string ToP2PKHAddress(this Hash160 hash, Span <byte> versionBytes)
        {
            Span <byte> data = new byte[versionBytes.Length + hash.Bytes.Length];

            versionBytes.CopyTo(data);
            hash.Bytes.CopyTo(data.Slice(versionBytes.Length, hash.Bytes.Length));
            return(Base58CheckEncoding.Encode(data));
        }
 public BalanceToken BalanceTokenModel(TokenBalance model)
 {
     return(new BalanceToken
     {
         Code = model.Code,
         Token = Base58CheckEncoding.EncodePlain(model.Token),
         Balance = model.Balance
     });
 }
Exemple #24
0
        public async Task TestCreateMyDidWorksForEmptyJson()
        {
            var result = await Signus.CreateAndStoreMyDidAsync(wallet, "{}");

            Assert.IsNotNull(result);

            Assert.AreEqual(16, Base58CheckEncoding.DecodePlain(result.Did).Length);
            Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(result.VerKey).Length);
        }
Exemple #25
0
 public void Decode()
 {
     foreach (var tuple in _testCases)
     {
         var text          = tuple.Item1;
         var expectedBytes = tuple.Item2;
         var actualBytes   = Base58CheckEncoding.DecodePlain(text);
         Assert.AreEqual(BitConverter.ToString(expectedBytes), BitConverter.ToString(actualBytes));
     }
 }
Exemple #26
0
 public void Encode()
 {
     foreach (var tuple in _testCases)
     {
         var bytes        = tuple.Item2;
         var expectedText = tuple.Item1;
         var actualText   = Base58CheckEncoding.EncodePlain(bytes);
         Assert.AreEqual(expectedText, actualText);
     }
 }
        public void EncodePlan_And_DecodePlain_ByteString()
        {
            var bs            = ByteString.CopyFromUtf8("test byte string");
            var encodeMessage = Base58CheckEncoding.EncodePlain(bs);

            var decodeMessage = Base58CheckEncoding.DecodePlain(encodeMessage);
            var bs1           = ByteString.CopyFrom(decodeMessage);

            bs.ShouldBe(bs1);
        }
        public void TestEncoding()
        {
            // Example address from https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses
            var          addressBytes   = "00f54a5851e9372b87810a8e60cdd2e7cfd80b6e31".HexToBytes();
            const string base58Expected = "1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs";

            var base58Actual = Base58CheckEncoding.Encode(addressBytes);

            base58Actual.Should().BeEquivalentTo(base58Expected);
        }
Exemple #29
0
 public API_TokenTransferTransInfo_4_3(TokenTransferTransInfo I)
 {
     Code             = I.Code;
     Sender           = Base58CheckEncoding.EncodePlain(I.Sender);
     Receiver         = Base58CheckEncoding.EncodePlain(I.Receiver);
     Amount           = I.Amount;
     State            = (API_SmartOperationState)I.State;
     StateTransaction = ConvertTransactionId(I.StateTransaction);
     TransferSuccess  = I.TransferSuccess;
 }
        public void TestEncode()
        {
            byte[]     message         = UTF8Encoding.UTF8.GetBytes("hello world");
            string     expected_header = "header-part ";
            string     expected_footer = " footer part.";
            string     expected_result = expected_header + Base58CheckEncoding.Encode(message) + expected_footer;
            SimplePack packer          = new SimplePack(expected_header, expected_footer);
            string     actual_result   = packer.encode(message);

            Assert.AreEqual(actual_result, expected_result);
        }