public async Task <BancardResponse> ZimpleSingleBuyAsync(BancardZimpleSingleBuyRequest request, CancellationToken cancellationToken = default)
        {
            var model = new RequestApiModel <ZimpleSingleBuyOperationApiModel>
            {
                PublicKey = _configuration.PublicKey,
                Operation = new ZimpleSingleBuyOperationApiModel
                {
                    Token          = HashHelper.SingleBuy(_configuration.PrivateKey, request.ShopProcessId, request.Amount, request.Currency.Value),
                    Currency       = request.Currency.Value,
                    Amount         = request.Amount.ToString("F2"),
                    ShopProcessId  = request.ShopProcessId,
                    AdditionalData = request.AdditionalData,
                    ReturnUrl      = request.ReturnUrl,
                    CancelUrl      = request.CancelUrl,
                    Description    = request.Description,
                    Zimple         = "S"
                }
            };

            var response = await _httpClient.ZimpleSingleBuy(model, cancellationToken);

            var responseBody = await response.Content.ReadAsAsync <ResponseApiModel>(cancellationToken);

            return(MapResponse(responseBody, response.IsSuccessStatusCode));
        }
        // [AuthKey]
        /// <summary>
        /// Упаковка транзакции
        ///  Base58Check
        /// .Base58CheckEncoding
        /// .EncodePlain(BCTransactionTools.CreateByteHashByTransaction(transac))
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public IActionResult Pack(RequestApiModel model)
        {
            // Нужна проверка валидности AuthKey - guid

            InitAuthKey(model);
            ResponseApiModel res = new ResponseApiModel();


            if (model.DelegateDisable || model.DelegateEnable || model.DateExpired != null)
            {
                res.DataResponse.TransactionPackagedStr = ServiceProvider
                                                          .GetService <TransactionService>().PackTransactionByApiModelDelegation(model);
            }
            else
            {
                res.DataResponse = ServiceProvider
                                   .GetService <TransactionService>().PackTransactionByApiModel(model);
            }

            res.Success = true;

            //TODO: запись в базу, для логов. Обработка ошибок. Согласовать стандарт.

            return(new JsonResult(res));//"value";
        }
Esempio n. 3
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));
        }
        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);
        }
        public string PackTransactionByApiModelDelegation(RequestApiModel model)
        {
            var transac = InitTransaction(model);
            var res     = SimpleBase.Base58.Bitcoin.Encode(BCTransactionTools.CreateByteHashByTransactionDelegation(transac, model.DelegateEnable, model.DelegateDisable));

            return(res);
        }
        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);
        }
        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);
            }
        }
Esempio n. 8
0
        public Task <HttpResponseMessage> CardsNew(RequestApiModel <CardsNewOperationApiModel> body, CancellationToken cancellationToken = default)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "/vpos/api/0.3/cards/new")
            {
                Content = new StringContent(JsonSerializer.Serialize(body))
            };

            return(_httpClient.SendAsync(request, cancellationToken));
        }
Esempio n. 9
0
        public Task <HttpResponseMessage> UsersCards(int userId, RequestApiModel <UsersCardsOperationApiModel> body, CancellationToken cancellationToken = default)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, $"/vpos/api/0.3/users/{userId}/cards")
            {
                Content = new StringContent(JsonSerializer.Serialize(body))
            };

            return(_httpClient.SendAsync(request, cancellationToken));
        }
Esempio n. 10
0
        public IActionResult Execute(RequestApiModel model)
        {
            var res = ServiceProvider
                      .GetService <TransactionService>()
                      .ExecuteTransaction(model);

            res.FlowResult = null;
            return(new JsonResult(res));//"value";
        }
        public async Task <BancardChargeResponse?> Charge(BancardChargeRequest request, CancellationToken cancellationToken = default)
        {
            var model = new RequestApiModel <ChargeOperationApiModel>
            {
                PublicKey = _configuration.PublicKey,
                Operation = new ChargeOperationApiModel
                {
                    Token            = HashHelper.Charge(_configuration.PrivateKey, request.ShopProcessId, request.Amount, request.Currency.Value, request.AliasToken),
                    Amount           = request.Amount.ToString("F2"),
                    Currency         = request.Currency.Value,
                    Description      = request.Description,
                    AdditionalData   = request.AdditionalData,
                    AliasToken       = request.AliasToken,
                    NumberOfPayments = request.NumberOfPayments,
                    ShopProcessId    = request.ShopProcessId
                }
            };
            var response = await _httpClient.Charge(model, cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                var stuff = MapResponse(await response.Content.ReadAsAsync <ResponseApiModel>(cancellationToken), response.IsSuccessStatusCode);
                return(new BancardChargeResponse
                {
                    IsSuccessful = response.IsSuccessStatusCode,
                    BancardResponse = stuff
                });
            }
            var responseBody = await response.Content.ReadAsAsync <ChargeResponseApiModel>(cancellationToken);

            var chargeResponse = new BancardChargeResponse
            {
                IsSuccessful        = true,
                Amount              = responseBody.Confirmation.Amount,
                Currency            = responseBody.Confirmation.Currency,
                Response            = responseBody.Confirmation.Response,
                Token               = responseBody.Confirmation.Token,
                AuthorizationNumber = responseBody.Confirmation.AuthorizationNumber,
                ResponseCode        = responseBody.Confirmation.ResponseCode,
                ResponseDescription = responseBody.Confirmation.ResponseDescription,
                ResponseDetails     = responseBody.Confirmation.ResponseDetails,
                SecurityInformation = new BancardSecurityInformation
                {
                    Version     = responseBody.Confirmation.SecurityInformation.Version,
                    CardCountry = responseBody.Confirmation.SecurityInformation.CardCountry,
                    CardSource  = responseBody.Confirmation.SecurityInformation.CardSource,
                    CustomerIp  = responseBody.Confirmation.SecurityInformation.CustomerIp,
                    RiskIndex   = responseBody.Confirmation.SecurityInformation.RiskIndex,
                },
                TicketNumber = responseBody.Confirmation.TicketNumber,
                ExtendedResponseDescription = responseBody.Confirmation.ExtendedResponseDescription,
                ShopProcessId = responseBody.Confirmation.ShopProcessId
            };

            return(chargeResponse);
        }
Esempio n. 12
0
        public Task <HttpResponseMessage> SingleBuyConfirm(RequestApiModel <SingleBuyConfirmationApiModel> body,
                                                           CancellationToken cancellationToken = default)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "/vpos/api/0.3/single_buy/confirmations")
            {
                Content = new StringContent(JsonSerializer.Serialize(body))
            };

            return(_httpClient.SendAsync(request, cancellationToken));
        }
Esempio n. 13
0
        public IActionResult Pack(RequestApiModel model)
        {
            ResponseApiModel res = new ResponseApiModel();


            res.DataResponse.TransactionPackagedStr = ServiceProvider
                                                      .GetService <TransactionService>()
                                                      .PackTransactionByApiModel(model).TransactionPackagedStr;//changed to model
            res.Success = true;

            return(new JsonResult(res));//"value";
        }
        public async Task <BancardConfirmationResponse> GetSingleBuyConfirmation(int shopProcessId, CancellationToken cancellationToken = default)
        {
            var model = new RequestApiModel <SingleBuyConfirmationApiModel>
            {
                PublicKey = _configuration.PublicKey,
                Operation = new SingleBuyConfirmationApiModel
                {
                    Token         = HashHelper.SingleBuyGetConfirmation(_configuration.PrivateKey, shopProcessId),
                    ShopProcessId = shopProcessId
                }
            };
            var response = await _httpClient.SingleBuyConfirm(model, cancellationToken);

            var responseBody = await response.Content.ReadAsAsync <SingleBuyConfirmationResponseApiModel>(cancellationToken);

            var returnModel = new BancardConfirmationResponse
            {
                IsSuccessStatusCode = response.IsSuccessStatusCode,
                Status   = responseBody.Status ?? "error",
                Messages = responseBody?.Messages?.Select(x => new BancardMessage
                {
                    Key         = x.Key,
                    Level       = x.Level,
                    Description = x.Dsc
                }).ToList() ?? new List <BancardMessage>(),
                Confirmation = new BancardConfirmationInfo
                {
                    Token                       = responseBody?.Confirmation.Token ?? "",
                    Amount                      = responseBody?.Confirmation.Amount ?? "",
                    Currency                    = BancardCurrency.Parse(responseBody?.Confirmation.Currency ?? "PYG"),
                    Response                    = responseBody?.Confirmation.Response ?? "",
                    AuthorizationNumber         = responseBody?.Confirmation.AuthorizationNumber ?? "",
                    ResponseCode                = responseBody?.Confirmation.ResponseCode ?? "",
                    ResponseDescription         = responseBody?.Confirmation.ResponseDescription ?? "",
                    ResponseDetails             = responseBody?.Confirmation.ResponseDetails ?? "",
                    ExtentedResponseDescription = responseBody?.Confirmation.ExtentedResponseDescription ?? "",
                    ShopProcessId               = responseBody?.Confirmation.ShopProcessId ?? 0,
                    SecurityInformation         = new BancardSecurityInformation
                    {
                        Version     = responseBody?.Confirmation.SecurityInformation.Version ?? "",
                        CardCountry = responseBody?.Confirmation.SecurityInformation.CardCountry ?? "",
                        CardSource  = responseBody?.Confirmation.SecurityInformation.CardSource ?? "",
                        CustomerIp  = responseBody?.Confirmation.SecurityInformation.CustomerIp ?? "",
                        RiskIndex   = responseBody?.Confirmation.SecurityInformation.RiskIndex ?? 0
                    }
                }
            };

            return(returnModel);
        }
        public async Task <BancardResponse> Delete(int userId, string aliasToken, CancellationToken cancellationToken = default)
        {
            var model = new RequestApiModel <DeleteOperationApiModel>
            {
                PublicKey = _configuration.PublicKey,
                Operation = new DeleteOperationApiModel
                {
                    Token      = HashHelper.Delete(_configuration.PrivateKey, userId, aliasToken),
                    AliasToken = aliasToken
                }
            };
            var response = await _httpClient.DeleteCard(userId, model, cancellationToken);

            var responseBody = await response.Content.ReadAsAsync <ResponseApiModel>(cancellationToken);

            return(MapResponse(responseBody, response.IsSuccessStatusCode));
        }
        public async Task <BancardResponse> SingleBuyRollback(int shopProcessId, CancellationToken cancellationToken = default)
        {
            var model = new RequestApiModel <SingleBuyRollbackApiModel>
            {
                PublicKey = _configuration.PublicKey,
                Operation = new SingleBuyRollbackApiModel
                {
                    Token         = HashHelper.SingleBuyRollback(_configuration.PrivateKey, shopProcessId),
                    ShopProcessId = shopProcessId
                }
            };
            var response = await _httpClient.SingleBuyRollback(model, cancellationToken);

            var responseBody = await response.Content.ReadAsAsync <ResponseApiModel>(cancellationToken);

            return(MapResponse(responseBody, response.IsSuccessStatusCode));
        }
        // [AuthKey]
        /// <summary>
        /// Выполнение транзакции. Которая предварительно уже была упакована отправлена
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IActionResult Execute(RequestApiModel model)
        {
            // Нужна проверка валидности AuthKey - guid

            InitAuthKey(model);


            var res = ServiceProvider.GetService <TransactionService>()
                      .ExecuteTransaction(model);



            //TODO: запись в базу, для логов. Обработка ошибок. Согласовать стандарт.


            res.FlowResult = null;
            return(new JsonResult(res));//"value";
        }
        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);
            }
        }
        public async Task <BancardResponse> CardsNew(BancardCardsNewRequest request, CancellationToken cancellationToken = default)
        {
            var model = new RequestApiModel <CardsNewOperationApiModel>
            {
                PublicKey = _configuration.PublicKey,
                Operation = new CardsNewOperationApiModel
                {
                    Token         = HashHelper.CardsNew(_configuration.PrivateKey, request.CardId, request.UserId),
                    CardId        = request.CardId,
                    UserId        = request.UserId,
                    ReturnUrl     = request.ReturnUrl,
                    UserMail      = request.UserMail,
                    UserCellPhone = request.UserCellPhone
                }
            };
            var response = await _httpClient.CardsNew(model, cancellationToken);

            var responseBody = await response.Content.ReadAsAsync <ResponseApiModel>(cancellationToken);

            return(MapResponse(responseBody, response.IsSuccessStatusCode));
        }
        public DataResponseApiModel PackTransactionByApiModel(RequestApiModel model)
        {
            var res     = new DataResponseApiModel();
            var transac = InitTransaction(model);

            byte[] byteData;

            if (!model.DelegateEnable && !model.DelegateDisable)
            {
                byteData = BCTransactionTools.CreateByteHashByTransaction(transac);
            }
            else
            {
                byteData = BCTransactionTools.CreateByteHashByTransactionDelegation(transac);
            }

            res.TransactionPackagedStr = SimpleBase.Base58.Bitcoin.Encode(byteData);
            res.RecommendedFee         = model.Fee;
            res.ActualSum = model.Amount;
            return(res);
        }
        public async Task <BancardUserCardsResponse> UsersCard(int userId, CancellationToken cancellationToken = default)
        {
            var model = new RequestApiModel <UsersCardsOperationApiModel>
            {
                PublicKey = _configuration.PublicKey,
                Operation = new UsersCardsOperationApiModel
                {
                    Token = HashHelper.UsersCards(_configuration.PrivateKey, userId)
                }
            };
            var response = await _httpClient.UsersCards(userId, model, cancellationToken);

            var responseBody = await response.Content.ReadAsAsync <UserCardsResponseApiModel>(cancellationToken);

            var returnModel = new BancardUserCardsResponse
            {
                IsSuccessStatusCode = response.IsSuccessStatusCode,
                Status = responseBody.Status,
                Cards  = responseBody.Cards.Select(x => new BancardCard
                {
                    AliasToken       = x.AliasToken,
                    CardBrand        = x.CardBrand,
                    CardId           = x.CardId,
                    CardType         = x.CardType,
                    ExpirationDate   = x.ExpirationDate,
                    CardMaskedNumber = x.CardMaskedNumber
                }).ToList(),
                Messages = responseBody.Messages.Select(x => new BancardMessage
                {
                    Key         = x.Key,
                    Level       = x.Level,
                    Description = x.Dsc
                }).ToList()
            };

            return(returnModel);
        }
        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);
        }
        public ResponseApiModel ExecuteTransaction(RequestApiModel request, int isDelegate = 0)
        {
            ResponseApiModel response = null;

            using (var client = GetClientByModel(request))
            {
                //снова инициируем транзакцию
                var transac = InitTransaction(request);
                transac.Signature = SimpleBase.Base58.Bitcoin.Decode(request.TransactionSignature).ToArray();

                if (request.DelegateEnable && !request.DelegateDisable)
                {
                    transac.UserFields = new byte[15] {
                        0, 1, 5, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0
                    }
                }
                ;
                else if (request.DelegateDisable && !request.DelegateEnable)
                {
                    transac.UserFields = new byte[15] {
                        0, 1, 5, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0
                    }
                }
                ;

                TransactionFlowResult result = client.TransactionFlow(transac);
                response            = new ResponseApiModel();
                response.FlowResult = result;
                if (request.MethodApi == ApiMethodConstant.SmartDeploy)
                {
                    response.DataResponse.PublicKey = SimpleBase.Base58.Bitcoin.Encode(transac.Target);
                }
                if (result.Status.Code > 0)
                {
                    response.Success = false;
                    response.Message = result.Status.Message;
                }
                else
                {
                    response.Success            = true;
                    response.TransactionInnerId = transac.Id;
                    if (result.Id != null)
                    {
                        response.TransactionId = $"{result.Id.PoolSeq}.{result.Id.Index + 1}";
                    }
                    response.DataResponse.RecommendedFee = BCTransactionTools.GetDecimalByAmount(response.FlowResult.Fee);
                    if (response.DataResponse.RecommendedFee == 0)
                    {
                        response.DataResponse.RecommendedFee = MinTransactionFee;
                    }
                    var sum = BCTransactionTools.GetDecimalByAmount(transac.Amount);
                    if (sum > 0)
                    {
                        if (response.Amount == 0)
                        {
                            response.Amount = sum;
                        }
                        if (response.ActualSum == 0)
                        {
                            response.ActualSum = sum;
                        }
                    }
                    //TODO: extract fee from node
                    if (result.Fee != null)
                    {
                        response.ActualFee = BCTransactionTools.GetDecimalByAmount(result.Fee);
                        if (response.ActualFee == 0M)
                        {
                            response.ActualFee = MinTransactionFee;
                        }
                    }

                    if (result.ExtraFee != null)
                    {
                        response.ExtraFee = new List <EFeeItem>();
                        foreach (var eFee in result.ExtraFee)
                        {
                            var feeSum = BCTransactionTools.GetDecimalByAmount(eFee.Sum);
                            response.ExtraFee.Add(new EFeeItem()
                            {
                                Fee     = feeSum,
                                Comment = eFee.Comment
                            });
                        }
                    }
                    if (request.MethodApi == ApiMethodConstant.SmartMethodExecute)
                    {
                        if (result.Smart_contract_result != null)
                        {
                            try
                            {
                                response.DataResponse.SmartContractResult = result.Smart_contract_result.ToString();
                            }
                            catch (Exception ex)
                            {
                                response.DataResponse.SmartContractResult = "";
                            }
                        }
                    }
                }
            }

            return(response);
        }
    }
        public Transaction InitTransaction(RequestApiModel model)
        {
            Transaction transac = new Transaction();

            using (var client = GetClientByModel(model))
            {
                // отправитель
                var sourceByte = SimpleBase.Base58.Bitcoin.Decode(model.PublicKey);
                transac.Source = sourceByte.ToArray();

                if (model.Fee == 0)
                {
                    Decimal res;
                    if (!string.IsNullOrWhiteSpace(model.FeeAsString) && Decimal.TryParse(model.FeeAsString.Replace(",", "."), NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out res))
                    {
                        transac.Fee = BCTransactionTools.EncodeFeeFromDouble(Decimal.ToDouble(res));
                    }
                    else
                    {
                        transac.Fee = BCTransactionTools.EncodeFeeFromDouble(Decimal.ToDouble(model.Fee));
                    }
                }
                else
                {
                    transac.Fee = BCTransactionTools.EncodeFeeFromDouble(Decimal.ToDouble(model.Fee));
                }

                //transac.Fee = BCTransactionTools.EncodeFeeFromDouble(Decimal.ToDouble(model.Fee));

                transac.Currency = 1;
                // ЗАПРОС механизм присваивания транзакции
                transac.Id = client.WalletDataGet(sourceByte.ToArray()).WalletData.LastTransactionId + 1;
                if (!String.IsNullOrEmpty(model.UserData))
                {
                    transac.UserFields = SimpleBase.Base58.Bitcoin.Decode(model.UserData).ToArray();
                }
                //  transac.UserFields = Convert.FromBase64String(model.UserData);

                if (model.MethodApi == ApiMethodConstant.TransferCs)
                {
                    if (model.Amount == 0)
                    {
                        if (string.IsNullOrEmpty(model.AmountAsString))
                        {
                            transac.Amount = new Amount();
                        }
                        else
                        {
                            Decimal res;
                            if (Decimal.TryParse(model.AmountAsString.Replace(",", "."), NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out res))
                            {
                                transac.Amount = BCTransactionTools.GetAmountByDouble_C(res);
                            }
                            else
                            {
                                transac.Amount = BCTransactionTools.GetAmountByDouble_C(model.Amount);
                            }
                        }
                    }
                    else
                    {
                        transac.Amount = BCTransactionTools.GetAmountByDouble_C(model.Amount);
                    }

                    if (model.Fee == 0)
                    {
                        var minFee = MinTransactionFee;
                        if (model.Amount - minFee >= 0.0M)
                        {
                            model.Fee    = minFee;
                            model.Amount = model.Amount - minFee;
                            //GetActualFee(RequestFeeModel)
                            //ServiceProvider.GetService<MonitorService>().GetBalance(model);

                            transac.Fee    = BCTransactionTools.EncodeFeeFromDouble(Convert.ToDouble(minFee));
                            transac.Amount = BCTransactionTools.GetAmountByDouble_C(model.Amount);
                        }
                        else
                        {
                            throw new Exception("Fee is zero and couldn't be get from transaction sum");
                        }
                    }
                    transac.Target = SimpleBase.Base58.Bitcoin.Decode(model.ReceiverPublicKey).ToArray();
                }
                else if (model.MethodApi == ApiMethodConstant.SmartDeploy)
                {
                    transac.Amount = BCTransactionTools.GetAmountByDouble_C(0);
                    //  Byte[] byteSource = sourceByte;
                    IEnumerable <Byte> sourceCodeByte = sourceByte.ToArray();

                    sourceCodeByte = sourceCodeByte.Concat(BitConverter.GetBytes(transac.Id).Take(6));
                    // ЗАПРОС
                    var byteCodes =
                        client.SmartContractCompile(model.SmartContractSource);
                    if (byteCodes.Status.Code > 0)
                    {
                        throw new Exception(byteCodes.Status.Message);
                    }
                    foreach (var item in byteCodes.ByteCodeObjects)
                    {
                        sourceCodeByte = sourceCodeByte.Concat(item.ByteCode);
                    }

                    transac.Target        = Blake2s.ComputeHash(sourceCodeByte.ToArray());
                    transac.SmartContract = new SmartContractInvocation()
                    {
                        SmartContractDeploy = new SmartContractDeploy()
                        {
                            SourceCode      = model.SmartContractSource,
                            ByteCodeObjects = byteCodes.ByteCodeObjects
                        },
                    };
                }
                else if (model.MethodApi == ApiMethodConstant.SmartMethodExecute)
                {
                    var listParam      = new List <Variant>();
                    var contractParams = new List <TokenParamsApiModel>();
                    if (model.ContractParams.Count > model.TokenParams.Count)
                    {
                        foreach (var item in model.ContractParams)
                        {
                            var param = new Variant();

                            if (item.ValBool != null)
                            {
                                param.V_boolean = item.ValBool.Value;
                            }
                            else if (item.ValDouble != null)
                            {
                                param.V_double = item.ValDouble.Value;
                            }
                            else if (item.ValInt != null)
                            {
                                param.V_int = item.ValInt.Value;
                            }
                            else if (item.ValInt != null)
                            {
                                param.V_int = item.ValInt.Value;
                            }
                            else
                            {
                                param.V_string = item.ValString;
                            }
                            listParam.Add(param);
                        }
                    }
                    else
                    {
                        foreach (var item in model.TokenParams)
                        {
                            var param = new Variant();

                            if (item.ValBool != null)
                            {
                                param.V_boolean = item.ValBool.Value;
                            }
                            else if (item.ValDouble != null)
                            {
                                param.V_double = item.ValDouble.Value;
                            }
                            else if (item.ValInt != null)
                            {
                                param.V_int = item.ValInt.Value;
                            }
                            else if (item.ValInt != null)
                            {
                                param.V_int = item.ValInt.Value;
                            }
                            else
                            {
                                param.V_string = item.ValString;
                            }
                            listParam.Add(param);
                        }
                    }


                    transac.Amount = BCTransactionTools.GetAmountByDouble_C(0); // количество токенов фиксируем в параметрах
                    if (model.ContractPublicKey == null || model.ContractPublicKey == "")
                    {
                        transac.Target = SimpleBase.Base58.Bitcoin.Decode(model.TokenPublicKey).ToArray(); // в таргет публичный ключ Token
                    }
                    else
                    {
                        transac.Target = SimpleBase.Base58.Bitcoin.Decode(model.ContractPublicKey).ToArray(); // в таргет публичный ключ Contract
                    }

                    transac.SmartContract = new SmartContractInvocation()
                    {
                        Method = (model.ContractMethod == null || model.ContractMethod == "") ? model.TokenMethod : model.ContractMethod,
                        Params = listParam
                    };
                }
                else if (model.MethodApi == ApiMethodConstant.TransferToken)
                {
                    transac.Amount        = BCTransactionTools.GetAmountByDouble_C(0);                        // количество токенов фиксируем в параметрах
                    transac.Target        = SimpleBase.Base58.Bitcoin.Decode(model.TokenPublicKey).ToArray(); // в таргет публичный ключ токена
                    transac.SmartContract = new SmartContractInvocation()
                    {
                        Method = "transfer",
                        Params = new List <Variant>()
                        {
                            new Variant()
                            {
                                // адресат перевода
                                V_string = model.ReceiverPublicKey
                            },
                            new Variant()
                            {
                                V_string = model.Amount.ToString().Replace(",", ".")
                            }
                        }
                    };
                }
            }

            return(transac);
        }