public void TransferTokenTest()
        {
            var service = new TransactionService(Configuration);
            var rand    = new Random();

            for (int i = 0; i < 2; i++)
            {
                var privateKey = "ohPH5zghdzmRDxd978r7y6r8YFoTcKm1MgW2gzik3omCuZLysjwNjTd9hnGREFyQHqhShoU4ri7q748UgdwZpzA";

                var model = new RequestApiModel();
                model.PublicKey         = "FeFjpcsfHErXPk5HkfVcwH6zYaRT2xNytDTeSjfuVywt";
                model.ReceiverPublicKey = "HhhRGwgA3W5qcNFrLC3odC4GmbkQnhdEc5XPqBiRW3Wx";
                model.TokenPublicKey    = "FY8J5uSb2D3qX3iwUSvcUSGvrBGAvsrXxKxMQdFfpdmm";
                model.Amount            = Decimal.Parse((i + rand.Next(1, 5)).ToString());
                model.MethodApi         = ApiMethodConstant.TransferToken;
                model.NetworkIp         = "165.22.220.8";
                model.NetworkPort       = "9090";
                model.NetworkAlias      = "MainNet";
                model.Fee = 0.1m;
                string message = service.PackTransactionByApiModel(model).TransactionPackagedStr; //changed to model
                Assert.IsNotNull(message);

                Rebex.Security.Cryptography.Ed25519 crypt = new Rebex.Security.Cryptography.Ed25519();
                crypt.FromPrivateKey(SimpleBase.Base58.Bitcoin.Decode(privateKey).ToArray());
                model.TransactionSignature = SimpleBase.Base58.Bitcoin.Encode(
                    crypt.SignMessage(SimpleBase.Base58.Bitcoin.Decode(message).ToArray())
                    );   // подписываем транзакцию

                var response = service.ExecuteTransaction(model);
                Assert.IsNotNull(response);
            }
        }
        public void SmartDeployTest()
        {
            var service    = new TransactionService(Configuration);
            var privateKey = "ohPH5zghdzmRDxd978r7y6r8YFoTcKm1MgW2gzik3omCuZLysjwNjTd9hnGREFyQHqhShoU4ri7q748UgdwZpzA";
            var model      = new RequestApiModel();

            model.PublicKey = "FeFjpcsfHErXPk5HkfVcwH6zYaRT2xNytDTeSjfuVywt";
            // model.RecieverPublicKey = "DM79n9Lbvm3XhBf1LwyBHESaRmJEJez2YiL549ArcHDC";
            // model.TokenPublicKey = "FY8J5uSb2D3qX3iwUSvcUSGvrBGAvsrXxKxMQdFfpdmm";
            model.Amount              = 0;
            model.MethodApi           = ApiMethodConstant.SmartDeploy;
            model.Fee                 = 0.9m;
            model.SmartContractSource = GetDefaultSmartByCustomData("TS2", "TEST1", "55555");
            model.NetworkIp           = "165.22.220.8";
            model.NetworkPort         = "9090";
            model.NetworkAlias        = "MainNet";
            string message = service.PackTransactionByApiModel(model).TransactionPackagedStr;//changed to model

            Assert.IsNotNull(message);

            Rebex.Security.Cryptography.Ed25519 crypt = new Rebex.Security.Cryptography.Ed25519();
            crypt.FromPrivateKey(SimpleBase.Base58.Bitcoin.Decode(privateKey).ToArray());
            model.TransactionSignature = SimpleBase.Base58.Bitcoin.Encode(
                crypt.SignMessage(SimpleBase.Base58.Bitcoin.Decode(message).ToArray())
                ); // подписываем транзакцию


            var response = service.ExecuteTransaction(model);


            Assert.IsNotNull(response);
        }
        private void TransferCsTest(decimal fee = 0.03m, string feeAsString = "")
        {
            var service    = new TransactionService(Configuration);
            var privateKey = "3Ki86Y3dy8enEgM1LXL97oQ6zLnhVbjJPpWAdqhgkAh7uFab37ergRWJxyDDsa46ra3UiQXqe2rW7JrJPkekBWMs";
            var model      = new RequestApiModel();

            model.PublicKey         = "H5ptdUUfjJBGiK2X3gN2EzNYxituCUUnXv2tiMdQKP3b";
            model.NetworkAlias      = "TestNet";
            model.ReceiverPublicKey = "9onQndywomSUr6iYKA2MS5pERcTJwEuUJys1iKNu13cH";
            model.Amount            = 1m;
            model.MethodApi         = ApiMethodConstant.TransferCs;
            model.Fee         = fee;
            model.FeeAsString = feeAsString;

            model.NetworkIp   = "68.183.230.109";
            model.NetworkPort = "9090";

            string message = service.PackTransactionByApiModel(model).TransactionPackagedStr;//changed to model

            Assert.IsNotNull(message);

            Rebex.Security.Cryptography.Ed25519 crypt = new Rebex.Security.Cryptography.Ed25519();
            crypt.FromPrivateKey(SimpleBase.Base58.Bitcoin.Decode(privateKey).ToArray());
            model.TransactionSignature = SimpleBase.Base58.Bitcoin.Encode(
                crypt.SignMessage(SimpleBase.Base58.Bitcoin.Decode(message).ToArray())
                ); // подписываем транзакцию

            var response = service.ExecuteTransaction(model);

            Assert.IsNotNull(response);
        }
Ejemplo n.º 4
0
 public Key(byte[] fromPublicKey)
 {
     _ed25519 = new Rebex.Security.Cryptography.Ed25519();
     _sha256  = new SHA256Managed();
     _ed25519.FromPublicKey(fromPublicKey);
     _publicKey = _ed25519.GetPublicKey();
 }
Ejemplo n.º 5
0
        private ResponseApiModel ExecSmartContractMethod(string tokenPublicKey, string tokenMethod, IEnumerable <TokenParamsApiModel> methodParams)
        {
            var service = new TransactionService(null);
            var model   = new RequestApiModel
            {
                NetworkIp      = networkIp,
                NetworkPort    = networkPort,
                PublicKey      = publicKey,
                TokenPublicKey = tokenPublicKey,
                Amount         = 0M,
                MethodApi      = ApiMethodConstant.SmartMethodExecute,
                Fee            = 0.1m,
                ContractMethod = tokenMethod
            };

            if (methodParams != null)
            {
                foreach (var tokenParamsApiModel in methodParams)
                {
                    model.ContractParams.Add(tokenParamsApiModel);
                }
            }

            string message = service.PackTransactionByApiModel(model).TransactionPackagedStr;//changed to model

            Assert.IsNotNull(message);

            Rebex.Security.Cryptography.Ed25519 crypt = new Rebex.Security.Cryptography.Ed25519();
            crypt.FromPrivateKey(SimpleBase.Base58.Bitcoin.Decode(privateKey).ToArray());
            model.TransactionSignature = SimpleBase.Base58.Bitcoin.Encode(
                crypt.SignMessage(SimpleBase.Base58.Bitcoin.Decode(message).ToArray())
                );

            return(service.ExecuteTransaction(model));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Convert recovery phrase to SSB.Keys
        /// </summary>
        /// <param name="words"></param>
        /// <returns></returns>
        public Keys WordsToKeys(string words)
        {
            var wordArr = words.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var amount  = wordArr.Length;

            if (amount != 24 && amount != 48)
            {
                throw new ArgumentException("there should be 24 or 48 words");
            }
            var fixedWords = string.Join(" ", SubArray(wordArr, 0, 24));

            BIP39 bip39 = new BIP39(fixedWords, "", BIP39.Language.English);
            var   seed  = bip39.EntropyBytes;

            Rebex.Security.Cryptography.Ed25519 ed25519 = new Rebex.Security.Cryptography.Ed25519();
            ed25519.FromSeed(seed);
            var secretKey = ed25519.GetPrivateKey();
            var publicKey = ed25519.GetPublicKey();

            var _public  = Convert.ToBase64String(publicKey) + ".ed25519";
            var _private = Convert.ToBase64String(secretKey) + ".ed25519";
            var keys     = new Keys
            {
                Curve   = "ed25519",
                Public  = _public,
                Private = _private,
                ID      = "@" + _public,
            };

            return(keys);
        }
Ejemplo n.º 7
0
        public static bool Verify(byte[] payload, Ed25519Signature signature)
        {
            var ed25519 = new Rebex.Security.Cryptography.Ed25519();

            ed25519.FromPublicKey(signature.PublicKey.HexToBytes());

            return(ed25519.VerifyMessage(payload, signature.Signature.HexToBytes()));
        }
Ejemplo n.º 8
0
        public Key(string seed = null)
        {
            _ed25519 = new Rebex.Security.Cryptography.Ed25519();
            _sha256  = new SHA256Managed();
            _ed25519.FromSeed(
                _sha256.ComputeHash(string.IsNullOrEmpty(seed) ? GetSeedKey() : Encoding.UTF8.GetBytes(seed)));

            _publicKey  = _ed25519.GetPublicKey();
            _privateKey = _ed25519.GetPrivateKey();
        }
Ejemplo n.º 9
0
Archivo: Form1.cs Proyecto: tkslan/Coin
        private void button1_Click(object sender, EventArgs e)
        {
            var timestamp = System.DateTime.UtcNow.ToFileTimeUtc().ToString();

            using (var hmacsha256 = new HMACSHA256(GetKey()))
            {
                hmacsha256.Initialize();
                var hash    = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(textBox1.Text));
                var ed25519 = new Rebex.Security.Cryptography.Ed25519();
                ed25519.FromSeed(hash);
                label1.Text = $@"Key:{ByteToString( ed25519.GetPrivateKey())} Hash:{ByteToString(hash)}";
            }
        }
Ejemplo n.º 10
0
        public static Ed25519Signature Sign(byte[] payload, Ed25519Seed seed)
        {
            var ed25519 = new Rebex.Security.Cryptography.Ed25519();

            ed25519.FromSeed(seed.SecretKey.Take(32).ToArray());

            var signature = ed25519.SignMessage(payload);

            return(new Ed25519Signature
            {
                PublicKey = seed.KeyPair.PublicKey.ToHex(),
                Signature = signature.ToHex()
            });
        }
Ejemplo n.º 11
0
        public byte[] SignTransaction(byte[] PrivateKey, byte[] Message)
        {
            if (PrivateKey == null)
            {
                throw new Exception("PrivateKey is not be empty");
            }
            if (Message == null)
            {
                throw new Exception("Message is not be empty");
            }

            Rebex.Security.Cryptography.Ed25519 o = new Rebex.Security.Cryptography.Ed25519();
            o.FromPrivateKey(PrivateKey);
            return(o.SignMessage(Message));
        }
        public void ExecuteDelegationTest()
        {
            var rand = new Random();
            // for (int i = 0; i < 30; i++)
            {
                var service    = new TransactionService(Configuration);
                var privateKey = "ohPH5zghdzmRDxd978r7y6r8YFoTcKm1MgW2gzik3omCuZLysjwNjTd9hnGREFyQHqhShoU4ri7q748UgdwZpzA";
                // "3Ki86Y3dy8enEgM1LXL97oQ6zLnhVbjJPpWAdqhgkAh7uFab37ergRWJxyDDsa46ra3UiQXqe2rW7JrJPkekBWMs";
                var model = new RequestApiModel();
                model.PublicKey         = "FeFjpcsfHErXPk5HkfVcwH6zYaRT2xNytDTeSjfuVywt";
                model.NetworkAlias      = "MainNet";
                model.AuthKey           = "87cbdd85-b2e0-4cb9-aebf-1fe87bf3afdd";
                model.ReceiverPublicKey = "HhhRGwgA3W5qcNFrLC3odC4GmbkQnhdEc5XPqBiRW3Wx"; //"9onQndywomSUr6iYKA2MS5pERcTJwEuUJys1iKNu13cH"; //"HhhRGwgA3W5qcNFrLC3odC4GmbkQnhdEc5XPqBiRW3Wx";// //
                model.Amount            = 5m;                                             //Decimal.Parse("0," + (i + rand.Next(1, 5)).ToString());
                model.MethodApi         = ApiMethodConstant.TransferCs;
                model.Fee = 0.1m;

                // model.NetworkIp = "165.22.220.8";
                // model.NetworkPort = "9090";

                model.DelegateDisable = true;
                //   model.UserData =
                //  Convert.ToBase64String(Encoding.UTF8.GetBytes("sadf_#@!#$#;543534r42фвавафыва"));
                //Base58Check.Base58CheckEncoding.EncodePlain(Encoding.UTF8.GetBytes("{'test':'test'}"));
                //   Base58Check.Base58CheckEncoding.EncodePlain(Encoding.UTF8.GetBytes("sadf_#@!#$#;543534r42фвавафыва"));

                string message = service.PackTransactionByApiModelDelegation(model);
                Assert.IsNotNull(message);

                Rebex.Security.Cryptography.Ed25519 crypt = new Rebex.Security.Cryptography.Ed25519();
                crypt.FromPrivateKey(SimpleBase.Base58.Bitcoin.Decode(privateKey).ToArray());
                model.TransactionSignature = SimpleBase.Base58.Bitcoin.Encode(
                    crypt.SignMessage(SimpleBase.Base58.Bitcoin.Decode(message).ToArray())
                    );   // подписываем транзакцию

                var response = service.ExecuteTransaction(model, 2);


                Assert.IsNotNull(response);
            }
        }
Ejemplo n.º 13
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var o          = new Rebex.Security.Cryptography.Ed25519();
                var publicKey  = Base58Check.Base58CheckEncoding.EncodePlain(o.GetPublicKey());
                var privateKey = Base58Check.Base58CheckEncoding.EncodePlain(o.GetPrivateKey());

                var user = new ApplicationUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    FullName    = string.Format("{0} {1}.", model.LastName, model.FirstName.Substring(0, 1)),
                    PublicKey   = publicKey,
                    PrivateKey  = privateKey,
                    IsActivated = true,
                    ApiKey      = Guid.NewGuid().ToString()
                };

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public void SmartMethodExecuteTest()
        {
            var service    = new TransactionService(Configuration);
            var privateKey = "ohPH5zghdzmRDxd978r7y6r8YFoTcKm1MgW2gzik3omCuZLysjwNjTd9hnGREFyQHqhShoU4ri7q748UgdwZpzA";
            var model      = new RequestApiModel();

            model.PublicKey      = "FeFjpcsfHErXPk5HkfVcwH6zYaRT2xNytDTeSjfuVywt";
            model.TokenPublicKey = "FY8J5uSb2D3qX3iwUSvcUSGvrBGAvsrXxKxMQdFfpdmm";
            model.Amount         = 0;
            model.MethodApi      = ApiMethodConstant.SmartMethodExecute;
            model.Fee            = 0.1m;
            model.NetworkIp      = "165.22.220.8";
            model.NetworkPort    = "9090";
            model.NetworkAlias   = "MainNet";
            model.ContractMethod = "balanceOf";
            model.ContractParams.Add(new TokenParamsApiModel()
            {
                ValString = "FeFjpcsfHErXPk5HkfVcwH6zYaRT2xNytDTeSjfuVywt"
            });                                                                               //кастомер

            string message = service.PackTransactionByApiModel(model).TransactionPackagedStr; //changed to model

            Assert.IsNotNull(message);

            Rebex.Security.Cryptography.Ed25519 crypt = new Rebex.Security.Cryptography.Ed25519();
            crypt.FromPrivateKey(SimpleBase.Base58.Bitcoin.Decode(privateKey).ToArray());
            model.TransactionSignature = SimpleBase.Base58.Bitcoin.Encode(
                crypt.SignMessage(SimpleBase.Base58.Bitcoin.Decode(message).ToArray())
                ); // подписываем транзакцию


            var response = service.ExecuteTransaction(model);


            Assert.IsNotNull(response);
        }
Ejemplo n.º 15
0
        public void Crypto1Test()
        {
            var sourceStr   = "FeFjpcsfHErXPk5HkfVcwH6zYaRT2xNytDTeSjfuVywt";
            var sourceByte  = SimpleBase.Base58.Bitcoin.Decode(sourceStr).ToArray();
            var privateByte = SimpleBase.Base58.Bitcoin.Decode("ohPH5zghdzmRDxd978r7y6r8YFoTcKm1MgW2gzik3omCuZLysjwNjTd9hnGREFyQHqhShoU4ri7q748UgdwZpzA").ToArray();


            using (var _api = BCTransactionTools.CreateContextBC("165.22.220.8", 9090, 60000))
            {
                //   WalletDataGetResult WalletData = _api._connect.WalletDataGet(sourceByte);
                //   long transactionId = WalletData.WalletData.LastTransactionId + 1;
                var transactionId = _api.WalletDataGet(sourceByte).WalletData.LastTransactionId + 1;
                //     var connect = _api._connect;
                //   for (int i = 0; i <= 19; i++)
                {
                    transactionId++;
                    Transaction transac = new Transaction
                    {
                        Id     = transactionId,
                        Source = sourceByte,
                        Amount = BCTransactionTools.GetAmountByDouble_C(0.1M),
                        Fee    = BCTransactionTools.EncodeFeeFromDouble(0.1),

                        // если перевод смарта то таргет публичник смарта
                        Target = SimpleBase.Base58.Bitcoin.Decode("FY8J5uSb2D3qX3iwUSvcUSGvrBGAvsrXxKxMQdFfpdmm").ToArray(),
                        // если перевод CS - то адресат назначения.
                        //"DM79n9Lbvm3XhBf1LwyBHESaRmJEJez2YiL549ArcHDC"),
                        // UserFields = model.UserData
                    };
                    transac.UserFields = new byte[5];
                    #region ДЕПЛОЙ СМАРТА (убрать if при необходимости)
                    if (1 == 2)
                    {
                        string codeSmart  = "";
                        Byte[] byteSource = transac.Source;
                        //code
                        var byteCodes =
                            _api.SmartContractCompile(codeSmart);
                        if (byteCodes.Status.Code > 0)
                        {
                            throw new Exception(byteCodes.Status.Message);
                        }
                        foreach (var item in byteCodes.ByteCodeObjects)
                        {
                            byteSource.Concat(item.ByteCode);
                        }
                        transac.Target        = Blake2s.ComputeHash(byteSource);
                        transac.SmartContract = new SmartContractInvocation()
                        {
                            SmartContractDeploy = new SmartContractDeploy()
                            {
                                SourceCode      = codeSmart,
                                ByteCodeObjects = byteCodes.ByteCodeObjects
                            }
                        };
                    }

                    #endregion


                    #region ВЫЗОВ МЕТОДА СМАРТА (убрать if при необходимости)

                    if (1 == 2)
                    {
                        transac.SmartContract = new SmartContractInvocation()
                        {
                            Method = "transfer",
                            Params = new List <Variant>()
                            {
                                new Variant()
                                {
                                    // адресат перевода
                                    V_string = "DM79n9Lbvm3XhBf1LwyBHESaRmJEJez2YiL549ArcHDC"
                                               //      { Value = "DM79n9Lbvm3XhBf1LwyBHESaRmJEJez2YiL549ArcHDC", Key = "STRING" },
                                               //           new Credtis_Api_Connect.Model.ParamsCreateModel { Value = "0.5", Key = "STRING" }
                                },
                                new Variant()
                                {
                                    V_string = "0.5"
                                }
                            }
                        };
                    }

                    #endregion



                    transac.Currency = 1;
                    Console.WriteLine(SimpleBase.Base58.Bitcoin.Encode(BCTransactionTools.CreateByteHashByTransaction(transac)));

                    Rebex.Security.Cryptography.Ed25519 crypt = new Rebex.Security.Cryptography.Ed25519();
                    crypt.FromPrivateKey(privateByte);
                    // var b58 = new SimpleBase.Base58();


                    transac.Signature = crypt
                                        .SignMessage(BCTransactionTools.CreateByteHashByTransaction(transac));

                    Console.WriteLine();
                    Console.WriteLine(SimpleBase.Base58.Bitcoin.Encode(transac.Signature));
                    //  Console.WriteLine(BitConverter.ToString(transac.Signature)); // работает в старом вариант


                    //  var  _api1 = BCTransactionTools.CreateContextBC("165.22.220.8", 9090, 6000);
                    //   var res = _api.TransactionFlow(transac);
                    Console.WriteLine();
                    //  Console.WriteLine(BitConverter.ToString(BCTransactionTools.CreateByteHashByTransaction(transac)).Replace("-",""));
                    //      = Res1;
                }
            }
        }