public IActionResult GetAddressesBalances(string addresses, int minConfirmations)
        {
            try
            {
                string[] addressesArray = addresses.Split(',');

                this.logger.LogDebug("Asking data for {0} addresses.", addressesArray.Length);

                AddressBalancesResult result = this.addressIndexer.GetAddressBalances(addressesArray, minConfirmations);

                this.logger.LogDebug("Sending data for {0} addresses.", result.Balances.Count);

                return(this.Json(result));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult DisconnectPeer([FromBody] DisconnectPeerViewModel viewModel)
        {
            try
            {
                var          endpoint = viewModel.PeerAddress.ToIPEndPoint(this.network.DefaultPort);
                INetworkPeer peer     = this.connectionManager.ConnectedPeers.FindByEndpoint(endpoint);
                if (peer != null)
                {
                    var peerBehavior = peer.Behavior <IConnectionManagerBehavior>();
                    peer.Disconnect($"{endpoint} was disconnected via the API.");
                }

                return(this.Ok());
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #3
0
        public async Task <IActionResult> TumbleAsync([FromBody] TumbleRequest request)
        {
            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                await this.tumbleBitManager.TumbleAsync(request.OriginWalletName, request.DestinationWalletName);

                return(this.Ok());
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "An error occured starting tumbling session.", e.ToString()));
            }
        }
        public async Task <IActionResult> BalanceAsync(DestinationChain destinationChain, string account)
        {
            try
            {
                if (!this.ethCompatibleClientProvider.IsChainSupportedAndEnabled(destinationChain))
                {
                    return(this.Json($"{destinationChain} not enabled or supported!"));
                }

                IETHClient client = this.ethCompatibleClientProvider.GetClientForChain(destinationChain);

                return(this.Json((await client.GetErc20BalanceAsync(account).ConfigureAwait(false)).ToString()));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());

                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public async Task <IActionResult> GetMaturedBlockDepositsAsync([FromQuery(Name = "blockHeight")] int blockHeight)
        {
            if (!this.ModelState.IsValid)
            {
                IEnumerable <string> errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                SerializableResult <List <MaturedBlockDepositsModel> > depositsResult = await this.maturedBlocksProvider.RetrieveDepositsAsync(blockHeight).ConfigureAwait(false);

                return(this.Json(depositsResult));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception thrown calling /api/FederationGateway/{0}: {1}.", FederationGatewayRouteEndPoint.GetMaturedBlockDeposits, e.Message);
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, $"Could not re-sync matured block deposits: {e.Message}", e.ToString()));
            }
        }
        public IActionResult GetHistory([FromQuery] int maxEntriesToReturn)
        {
            try
            {
                FederationWallet wallet = this.walletManager.GetWallet();
                if (wallet == null)
                {
                    return(this.NotFound("No federation wallet found."));
                }

                List <WithdrawalModel> result = this.withdrawalHistoryProvider.GetHistory(maxEntriesToReturn);

                return(this.Json(result));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #7
0
        public async Task <IActionResult> ConnectAsync([FromBody] TumblerConnectionRequest request)
        {
            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                var tumblerParameters = await this.tumbleBitManager.ConnectToTumblerAsync(request.ServerAddress);

                return(this.Json(tumblerParameters));
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, $"An error occured connecting to the tumbler with uri {request.ServerAddress}.", e.ToString()));
            }
        }
Example #8
0
        public IActionResult Recover([FromBody] WalletRecoveryRequest request)
        {
            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                // get the wallet folder
                DirectoryInfo walletFolder = GetWalletFolder(request.FolderPath);

                Wallet wallet = this.walletManager.RecoverWallet(request.Password, walletFolder.FullName, request.Name, request.Network, request.Mnemonic, null, request.CreationDate);

                // start syncing the wallet from the creation date
                this.tracker.SyncFrom(request.CreationDate);

                return(this.Json(new WalletModel
                {
                    Network = wallet.Network.Name,
                    //	Addresses = wallet.GetFirstNAddresses(10).Select(a => a.ToWif()),
                    FileName = wallet.WalletFilePath
                }));
            }
            catch (InvalidOperationException e)
            {
                // indicates that this wallet already exists
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.Conflict, "This wallet already exists.", e.ToString()));
            }
            catch (FileNotFoundException e)
            {
                // indicates that this wallet does not exist
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.NotFound, "Wallet not found.", e.ToString()));
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #9
0
        public IActionResult Recover([FromBody] WalletRecoveryRequest request)
        {
            Guard.NotNull(request, nameof(request));
            this.logger.LogTrace("({0}.{1}:'{2}')", nameof(request), nameof(request.Name), request.Name);

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            try
            {
                Wallet wallet = this.walletManager.RecoverWallet(request.Password, request.Name, request.Mnemonic, request.CreationDate);

                this.SyncFromBestHeightForRecoveredWallets(request.CreationDate);

                return(this.Ok());
            }
            catch (WalletException e)
            {
                // indicates that this wallet already exists
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.Conflict, e.Message, e.ToString()));
            }
            catch (FileNotFoundException e)
            {
                // indicates that this wallet does not exist
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.NotFound, "Wallet not found.", e.ToString()));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
            finally
            {
                this.logger.LogTrace("(-)");
            }
        }
Example #10
0
        public IActionResult BuildTransaction([FromBody] BuildTransactionRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }
            var destination = BitcoinAddress.Create(request.DestinationAddress, this.network).ScriptPubKey;

            try
            {
                var context = new TransactionBuildContext(
                    new WalletAccountReference(request.WalletName, request.AccountName),
                    new[] { new Recipient {
                                Amount = request.Amount, ScriptPubKey = destination
                            } }.ToList(),
                    request.Password)
                {
                    FeeType          = FeeParser.Parse(request.FeeType),
                    MinConfirmations = request.AllowUnconfirmed ? 0 : 1
                };

                var transactionResult = this.walletTransactionHandler.BuildTransaction(context);

                var model = new WalletBuildTransactionModel
                {
                    Hex           = transactionResult.ToHex(),
                    Fee           = context.TransactionFee,
                    TransactionId = transactionResult.GetHash()
                };

                return(this.Json(model));
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult ListMethods()
        {
            try
            {
                var listMethods = new List <Models.RpcCommandModel>();
                foreach (ControllerActionDescriptor descriptor in this.GetActionDescriptors().Values.Where(desc => desc.ActionName == desc.ActionName.ToLower()))
                {
                    CustomAttributeData attr = descriptor.MethodInfo.CustomAttributes.Where(x => x.AttributeType == typeof(ActionDescription)).FirstOrDefault();
                    string description       = attr?.ConstructorArguments.FirstOrDefault().Value as string ?? "";

                    var parameters = new List <string>();
                    foreach (ControllerParameterDescriptor param in descriptor.Parameters.OfType <ControllerParameterDescriptor>())
                    {
                        if (!param.ParameterInfo.IsRetval)
                        {
                            string value = $"<{param.ParameterInfo.Name.ToLower()}>";

                            if (param.ParameterInfo.HasDefaultValue)
                            {
                                value = $"[{value}]";
                            }

                            parameters.Add(value);
                        }
                    }

                    string method = $"{descriptor.ActionName} {string.Join(" ", parameters.ToArray())}";

                    listMethods.Add(new Models.RpcCommandModel {
                        Command = method.Trim(), Description = description
                    });
                }

                return(this.Json(listMethods));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        private IActionResult VoteAddKickFedMember(CollateralFederationMemberModel request, bool addMember)
        {
            Guard.NotNull(request, nameof(request));

            if (!this.ModelState.IsValid)
            {
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            if (!this.fedManager.IsFederationMember)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Only federation members can vote", string.Empty));
            }

            try
            {
                var key = new PubKey(request.PubKeyHex);

                if (this.fedManager.IsMultisigMember(key))
                {
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Multisig members can't be voted on", string.Empty));
                }

                IFederationMember federationMember = new CollateralFederationMember(key, false, new Money(request.CollateralAmountSatoshis), request.CollateralMainchainAddress);

                byte[] fedMemberBytes = (this.network.Consensus.ConsensusFactory as PoAConsensusFactory).SerializeFederationMember(federationMember);

                this.votingManager.ScheduleVote(new VotingData()
                {
                    Key  = addMember ? VoteKey.AddFederationMember : VoteKey.KickFederationMember,
                    Data = fedMemberBytes
                });

                return(this.Ok());
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "There was a problem executing a command.", e.ToString()));
            }
        }
        public async Task <IActionResult> GetTransactionsAsync()
        {
            if (!this.ModelState.IsValid)
            {
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            var pageSize = 10; // Should we allow page size to be set in query?

            //this.logger.LogTrace("(Hash:'{1}')", hash);

            try
            {
                ChainedHeader chainHeader = this.chain.Tip;

                var transactions = new List <TransactionVerboseModel>();

                while (chainHeader != null && transactions.Count < pageSize)
                {
                    Block block = this.blockStoreCache.GetBlock(chainHeader.HashBlock);

                    var blockModel = new PosBlockModel(block, this.chain);

                    foreach (Transaction trx in block.Transactions)
                    {
                        // Since we got Chainheader and Tip available, we'll supply those in this query. That means this query will
                        // return more metadata than specific query using transaction ID.
                        transactions.Add(new TransactionVerboseModel(trx, this.network, chainHeader, this.chainState.BlockStoreTip));
                    }

                    chainHeader = chainHeader.Previous;
                }

                return(Json(transactions));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public ActionResult RegisterUser(RegisterUserViewModel registerUserViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var url = $"{ProjectConstants.APIURL}/api/Account/Register";

            var parameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", registerUserViewModel.Email),
                new KeyValuePair <string, string>("Password", registerUserViewModel.Password),
                new KeyValuePair <string, string>("ConfirmPassword", registerUserViewModel.ConfirmPassword)
            };

            // x-www-form-encoded tag, just like in post man, so that the data is sent on the body.
            var encodedParameters = new FormUrlEncodedContent(parameters);

            // Handling lack of connection??? try catch?
            var response = HttpClientContext.httpClient.PostAsync(url, encodedParameters).Result;

            if (response.IsSuccessStatusCode)
            {
                if (!LogUserIn(registerUserViewModel.Email, registerUserViewModel.Password))
                {
                    ModelState.AddModelError("", "There was an error logging you in..");
                    return(View());
                }
                else
                {
                    TempData.Add("Message", "Account Created!");
                    return(RedirectToAction("Index", "Household"));
                }
            }
            else
            {
                ErrorHelpers.HandleResponseErrors(response, TempData, ModelState);
                return(View());
            }
        }
Example #15
0
        public IActionResult StartStaking([FromBody] StartStakingRequest request)
        {
            Guard.NotNull(request, nameof(request));

            try
            {
                if (!this.fullNode.Network.Consensus.IsProofOfStake)
                {
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.MethodNotAllowed, "Method not allowed",
                                                           "Method not available for Proof of Stake"));
                }

                if (!this.ModelState.IsValid)
                {
                    var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error",
                                                           string.Join(Environment.NewLine, errors)));
                }

                var wallet = this.walletManager.GetWallet(request.Name);

                // Check the password
                try
                {
                    Key.Parse(wallet.EncryptedSeed, request.Password, wallet.Network);
                }
                catch (Exception ex)
                {
                    throw new SecurityException(ex.Message);
                }

                this.fullNode.NodeFeature <MiningFeature>(true).StartStaking(request.Name, request.Password);

                return(Ok());
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult BuildTransaction([FromBody] BuildMultisigTransactionRequest request)
        {
            Guard.NotNull(request, nameof(request));

            if (!this.ModelState.IsValid)
            {
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            try
            {
                var recipients = request
                                 .Recipients
                                 .Select(recipientModel => new Wallet.Recipient
                {
                    ScriptPubKey = BitcoinAddress.Create(recipientModel.DestinationAddress, this.network).ScriptPubKey,
                    Amount       = recipientModel.Amount
                })
                                 .ToList();

                Key[] privateKeys = request
                                    .Secrets
                                    .Select(secret => new Mnemonic(secret.Mnemonic).DeriveExtKey(secret.Passphrase).PrivateKey)
                                    .ToArray();

                Transaction transactionResult = this.fedMultiSigManualWithdrawalTransactionBuilder.BuildTransaction(recipients, privateKeys);

                var model = new WalletBuildTransactionModel
                {
                    Hex           = transactionResult.ToHex(),
                    TransactionId = transactionResult.GetHash()
                };

                return(this.Json(model));
            }
            catch (Exception e)
            {
                LoggerExtensions.LogError(this.logger, "Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #17
0
        public async Task <IActionResult> GetRawTransactionAsync([FromQuery] string trxid, bool verbose = false)
        {
            try
            {
                Guard.NotEmpty(trxid, nameof(trxid));

                uint256 txid;
                if (!uint256.TryParse(trxid, out txid))
                {
                    throw new ArgumentException(nameof(trxid));
                }

                // First tries to find a pooledTransaction. If can't, will retrieve it from the blockstore if it exists.
                Transaction trx = this.pooledTransaction != null ? await this.pooledTransaction.GetTransaction(txid).ConfigureAwait(false) : null;

                if (trx == null)
                {
                    trx = this.blockStore?.GetTransactionById(txid);
                }

                if (trx == null)
                {
                    return(this.Json(null));
                }

                if (verbose)
                {
                    ChainedHeader block = this.GetTransactionBlock(txid, this.fullNode, this.chainIndexer);
                    return(this.Json(new TransactionVerboseModel(trx, this.network, block, this.chainState?.ConsensusTip)));
                }
                else
                {
                    return(this.Json(new TransactionBriefModel(trx)));
                }
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #18
0
        public IActionResult ImportMemberKey([FromBody] ImportMemberKeyRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(BuildErrorResponse(this.ModelState));
            }

            try
            {
                this.walletManager.ImportMemberKey(request.Password, request.Mnemonic, request.Passphrase);
                return(this.Ok());
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public async Task <IActionResult> GetTumblingStateAsync()
        {
            try
            {
                var parameterDictionary = new Dictionary <string, string>()
                {
                    ["tumbler"]           = this.tumbleBitManager.TumblerAddress,
                    ["state"]             = this.tumbleBitManager.State.ToString(),
                    ["originWallet"]      = this.tumbleBitManager.tumblingState.OriginWalletName,
                    ["destinationWallet"] = this.tumbleBitManager.tumblingState.DestinationWalletName,
                    ["registrations"]     = this.tumbleBitManager.RegistrationCount().ToString(),
                    ["minRegistrations"]  = "1"
                };

                return(this.Json(parameterDictionary));
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "An error occured during tumbling-state request.", e.ToString()));
            }
        }
        public IActionResult GetUnusedAddress([FromQuery] GetUnusedAddressModel request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                var result = this.walletManager.GetUnusedAddress(new WalletAccountReference(request.WalletName, request.AccountName));
                return(this.Json(result.Address));
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult CreateNewAccount([FromBody] GetUnusedAccountModel request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(BuildErrorResponse(this.ModelState));
            }

            try
            {
                var result = this.walletManager.GetUnusedAccount(request.WalletName, request.Password);
                return(this.Json(result.Name));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #22
0
        public IActionResult Deserialize([FromBody] DeserializeTransactionRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            try
            {
                Transaction transaction = this.network.CreateTransaction(request.Hex);
                return(Content(transaction.ToString(this.network)));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #23
0
        public IActionResult GetAddressesBalances(string addresses, int minConfirmations)
        {
            try
            {
                string[] addressesArray = addresses.Split(',');

                var balances = new Dictionary <string, Money>(addresses.Length);

                foreach (string address in addressesArray)
                {
                    balances[address] = this.addressIndexer.GetAddressBalance(address, minConfirmations);
                }

                return(this.Json(balances));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult GetStakingInfo()
        {
            try
            {
                // checks the request is valid
                if (!this.ModelState.IsValid)
                {
                    var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
                }

                GetStakingInfoModel model = this.posMinting != null?this.posMinting.GetGetStakingInfoModel() : new GetStakingInfoModel();

                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult GetHistoryFilter([FromQuery] WalletHistoryFilterRequest request)
        {
            Guard.NotNull(request, nameof(request));

            if (!this.ModelState.IsValid)
            {
                return(ModelStateErrors.BuildErrorResponse(this.ModelState));
            }

            try
            {
                WalletHistoryFilterModel model = HistoryModelBuilder.GetHistoryFilter(this.chain, this.walletManager, this.blockRepository, this.txMempool, this.network, request);

                return(this.Json(model));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Example #26
0
        public IActionResult Rescan([FromQuery] DateTimeOffset fromTime)
        {
            try
            {
                RescanState rescanState = this.watchOnlyWalletManager.Rescan(fromTime);

                RescanStateModel model = new RescanStateModel()
                {
                    IsInProgress       = rescanState.IsInProgress,
                    FromTime           = rescanState.FromTime,
                    UntilTime          = rescanState.UntilTime,
                    ProgressPercentage = rescanState.ProgressPercentage
                };

                return(this.Json(model));
            }
            catch (Exception e)
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.Conflict, e.Message, e.ToString()));
            }
        }
        public IActionResult ListAccounts([FromQuery] ListAccountsModel request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(BuildErrorResponse(this.ModelState));
            }

            try
            {
                IEnumerable <HdAccount> result = this.walletManager.GetAccounts(request.WalletName);
                return(this.Json(result.Select(a => a.Name)));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult GetFederationAtHeight([FromQuery(Name = "blockHeight")] int blockHeight)
        {
            try
            {
                ChainedHeader            chainedHeader     = this.chainIndexer.GetHeader(blockHeight);
                List <IFederationMember> federationMembers = this.federationHistory.GetFederationForBlock(chainedHeader);
                List <PubKey>            federationPubKeys = new List <PubKey>();

                foreach (IFederationMember federationMember in federationMembers)
                {
                    federationPubKeys.Add(federationMember.PubKey);
                }

                return(Json(federationPubKeys));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        public IActionResult GetExtPubKey([FromQuery] GetExtPubKeyModel request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(BuildErrorResponse(this.ModelState));
            }

            try
            {
                string result = this.walletManager.GetExtPubKey(new WalletAccountReference(request.WalletName, request.AccountName));
                return(this.Json(result));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
 public IActionResult GetRegistrations()
 {
     try
     {
         List <IServiceNode>             serviceNodes = this.serviceNodeManager.GetServiceNodes();
         IEnumerable <RegistrationModel> models       = serviceNodes.Select(m => new RegistrationModel
         {
             ServerId        = m.RegistrationRecord.Token.ServerId,
             BlockReceived   = m.RegistrationRecord.BlockReceived,
             RecordTimestamp = m.RegistrationRecord.RecordTimestamp,
             RecordTxHex     = m.RegistrationRecord.RecordTxHex,
             RecordTxId      = m.RegistrationRecord.RecordTxId
         });
         return(this.Json(models));
     }
     catch (Exception e)
     {
         this.logger.LogError("Exception occurred: {0}", e.ToString());
         return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
     }
 }