Example #1
0
        /// <summary>
        /// Handle get request received from client.
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        private async Task HandlePacketHttpAsync(string packet)
        {
            if (packet.Contains("|"))
            {
                var splitPacket = packet.Split(new[] { "|" }, StringSplitOptions.None);

                switch (splitPacket[0])
                {
                case ClassApiEnumeration.GetPoolPaymentById:
                    if (int.TryParse(splitPacket[1], out var paymentId))
                    {
                        if (paymentId > 0)
                        {
                            paymentId--;
                        }
                        if (ClassMinerStats.DictionaryPoolTransaction.ContainsKey(paymentId))
                        {
                            var    payment  = ClassMinerStats.DictionaryPoolTransaction[paymentId].Split(new[] { "|" }, StringSplitOptions.None);
                            string hash     = payment[0];
                            string amount   = payment[1];
                            string fee      = payment[2];
                            string timeSent = payment[3];
                            Dictionary <string, string> paymentContent = new Dictionary <string, string>()
                            {
                                { "payment_id", splitPacket[1] },
                                { "payment_hash", hash },
                                { "payment_amount", ClassUtility.FormatMaxDecimalPlace(amount) },
                                { "payment_fee", ClassUtility.FormatMaxDecimalPlace(fee) },
                                { "payment_date_sent", timeSent }
                            };
                            await BuildAndSendHttpPacketAsync(string.Empty, true, paymentContent);

                            break;
                        }
                        else
                        {
                            await BuildAndSendHttpPacketAsync(ClassApiEnumeration.IndexNotExist);
                        }
                    }
                    else
                    {
                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                    }
                    break;

                case ClassApiEnumeration.GetPoolBlockById:
                    if (int.TryParse(splitPacket[1], out var blockId))
                    {
                        if (blockId > 0)
                        {
                            blockId--;
                        }
                        if (ClassMiningPoolGlobalStats.ListBlockFound.ContainsKey(blockId))
                        {
                            var blockFound  = ClassMiningPoolGlobalStats.ListBlockFound[blockId];
                            var splitBlock  = blockFound.Split(new[] { "|" }, StringSplitOptions.None);
                            var blockResult = await ClassRemoteApi.GetBlockInformation(splitBlock[0]);

                            if (blockResult != null)
                            {
                                try
                                {
                                    JObject jObjectBlock = JObject.Parse(blockResult);
                                    if (jObjectBlock.ContainsKey("result"))     // Usually showed has not exist when the remote node don't have finish to sync blocks mined.
                                    {
                                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.IndexNotExist);
                                    }
                                    else
                                    {
                                        await BuildAndSendHttpPacketAsync(blockResult, false, null, true);     // Send already jsonfyed request.
                                    }
                                }
                                catch (Exception error)
                                {
                                    ClassLog.ConsoleWriteLog("Pool API - Remote Node HTTP API packet exception: " + error.Message + " packet received: " + blockResult, ClassLogEnumeration.IndexPoolApiErrorLog, ClassLogConsoleEnumeration.IndexPoolConsoleRedLog);
                                    await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                                }
                            }
                            else
                            {
                                ClassLog.ConsoleWriteLog("Pool API - Warning, your Remote Node HTTP API seems to not respond !", ClassLogEnumeration.IndexPoolApiErrorLog, ClassLogConsoleEnumeration.IndexPoolConsoleRedLog, true);
                                await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                            }
                            break;
                        }
                        else
                        {
                            await BuildAndSendHttpPacketAsync(ClassApiEnumeration.IndexNotExist);
                        }
                    }
                    else
                    {
                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                    }
                    break;

                case ClassApiEnumeration.GetWalletPaymentById:
                    if (splitPacket.Length > 1)
                    {
                        if (ClassMinerStats.DictionaryMinerStats.ContainsKey(splitPacket[1]))
                        {
                            if (ClassMinerStats.DictionaryMinerTransaction.ContainsKey(splitPacket[1]))
                            {
                                if (int.TryParse(splitPacket[2], out var walletPaymentId))
                                {
                                    if (walletPaymentId > 0)
                                    {
                                        walletPaymentId--;
                                    }
                                    if (ClassMinerStats.DictionaryMinerTransaction[splitPacket[1]].Count > walletPaymentId)
                                    {
                                        var    paymentSplit        = ClassMinerStats.DictionaryMinerTransaction[splitPacket[1]][walletPaymentId].Split(new[] { "|" }, StringSplitOptions.None);
                                        string transactionHash     = paymentSplit[0];
                                        string transactionAmount   = paymentSplit[1];
                                        string transactionFee      = paymentSplit[2];
                                        string transactionDateSent = paymentSplit[3];
                                        Dictionary <string, string> paymentContent = new Dictionary <string, string>()
                                        {
                                            { "payment_hash", transactionHash },
                                            { "payment_amount", ClassUtility.FormatMaxDecimalPlace(transactionAmount) },
                                            { "payment_fee", ClassUtility.FormatMaxDecimalPlace(transactionFee) },
                                            { "payment_date_sent", transactionDateSent }
                                        };
                                        await BuildAndSendHttpPacketAsync(string.Empty, true, paymentContent);
                                    }
                                    else
                                    {
                                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.WalletPaymentIndexNotExist);
                                    }
                                }
                                else
                                {
                                    await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                                }
                            }
                            else
                            {
                                await BuildAndSendHttpPacketAsync(ClassApiEnumeration.WalletNoPaymentExist);
                            }
                        }
                        else
                        {
                            await BuildAndSendHttpPacketAsync(ClassApiEnumeration.WalletNotExist);
                        }
                    }
                    else
                    {
                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                    }
                    break;

                case ClassApiEnumeration.GetWalletStats:
                    if (splitPacket.Length > 1)
                    {
                        if (ClassMinerStats.DictionaryMinerStats.ContainsKey(splitPacket[1]))
                        {
                            int     totalPayment         = 0;
                            long    totalGoodShare       = 0;
                            float   totalInvalidShare    = 0;
                            string  totalBalance         = "0";
                            string  totalPaid            = "0";
                            decimal totalHashrate        = 0;
                            decimal totalMiningScore     = 0;
                            decimal totalMiningScorePool = 0;
                            decimal customMinimumPayment = 0;
                            long    lastShareReceived    = 0;

                            if (ClassMinerStats.DictionaryMinerTransaction.ContainsKey(splitPacket[1]))
                            {
                                totalPayment = ClassMinerStats.DictionaryMinerTransaction[splitPacket[1]].Count;
                            }
                            totalGoodShare       = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].TotalGoodShare;
                            totalInvalidShare    = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].TotalInvalidShare;
                            totalBalance         = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].TotalBalance.ToString("F" + ClassConnectorSetting.MaxDecimalPlace);
                            totalPaid            = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].TotalPaid.ToString("F" + ClassConnectorSetting.MaxDecimalPlace);
                            totalHashrate        = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].CurrentTotalHashrate;
                            totalMiningScore     = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].TotalMiningScore;
                            customMinimumPayment = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].CustomMinimumPayment;
                            lastShareReceived    = ClassMinerStats.DictionaryMinerStats[splitPacket[1]].DateOfLastGoodShare;
                            foreach (var minerStats in ClassMinerStats.DictionaryMinerStats)
                            {
                                if (minerStats.Value.TotalBan <= MiningPoolSetting.MiningPoolMaxTotalBanMiner)
                                {
                                    if (minerStats.Value.TotalMiningScore > 0)
                                    {
                                        totalMiningScorePool += minerStats.Value.TotalMiningScore;
                                    }
                                }
                            }
                            Dictionary <string, string> minerStatsContent = new Dictionary <string, string>()
                            {
                                { "wallet_address", splitPacket[1] },
                                { "wallet_total_hashrate", "" + totalHashrate },
                                { "wallet_total_good_share", "" + totalGoodShare },
                                { "wallet_total_invalid_share", "" + totalInvalidShare },
                                { "wallet_total_balance", totalBalance },
                                { "wallet_total_paid", totalPaid },
                                { "wallet_total_payment", "" + totalPayment },
                                { "wallet_total_mining_score", totalMiningScore.ToString("F0") },
                                { "wallet_total_pool_mining_score", totalMiningScorePool.ToString("F0") },
                                { "wallet_custom_minimum_payment", "" + customMinimumPayment },
                                { "wallet_last_share_received", "" + lastShareReceived }
                            };
                            await BuildAndSendHttpPacketAsync(string.Empty, true, minerStatsContent);

                            break;
                        }
                        else
                        {
                            await BuildAndSendHttpPacketAsync(ClassApiEnumeration.WalletNotExist);
                        }
                    }
                    else
                    {
                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                    }
                    break;

                case ClassApiEnumeration.SetWalletCustomMinimumPayment:
                    if (splitPacket.Length > 2)
                    {
                        if (ClassMinerStats.DictionaryMinerStats.ContainsKey(splitPacket[1]))
                        {
                            var customMinimumPaymentString = ClassUtility.FormatMaxDecimalPlace(splitPacket[2].Replace(".", ",")).Replace(".", ",");
                            if (decimal.TryParse(customMinimumPaymentString, NumberStyles.Currency, Program.GlobalCultureInfo, out var customMinimumPayment))
                            {
                                if (customMinimumPayment >= MiningPoolSetting.MiningPoolMinimumBalancePayment)
                                {
                                    ClassMinerStats.DictionaryMinerStats[splitPacket[1]].CustomMinimumPayment = customMinimumPayment;
                                    await BuildAndSendHttpPacketAsync(ClassApiEnumeration.CustomMinimumPaymentChanged);
                                }
                                else
                                {
                                    await BuildAndSendHttpPacketAsync(ClassApiEnumeration.CustomMinimumPaymentTooLowest);
                                }
                            }
                            else
                            {
                                await BuildAndSendHttpPacketAsync(ClassApiEnumeration.CustomMinimumPaymentNotValid);
                            }
                        }
                        else
                        {
                            await BuildAndSendHttpPacketAsync(ClassApiEnumeration.WalletNotExist);
                        }
                    }
                    else
                    {
                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                    }
                    break;

                default:
                    await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketNotExist);

                    break;
                }
            }
            else
            {
                switch (packet)
                {
                case ClassApiEnumeration.GetPoolStats:
                    decimal networkHashrate    = 0;
                    string  networkInformation = await ClassRemoteApi.GetNetworkInformation();

                    if (networkInformation != null)
                    {
                        var networkInformationObject = JObject.Parse(networkInformation);
                        networkHashrate = decimal.Parse(networkInformationObject["coin_network_hashrate"].ToString());
                        string lastBlockFoundDate = "0";
                        if (ClassMiningPoolGlobalStats.ListBlockFound.Count > 0)
                        {
                            lastBlockFoundDate = ClassMiningPoolGlobalStats.ListBlockFound[ClassMiningPoolGlobalStats.ListBlockFound.Count - 1].Split(new[] { "|" }, StringSplitOptions.None)[1];
                        }
                        var    lastBlockFound      = int.Parse(ClassMiningPoolGlobalStats.CurrentBlockId) - 1;
                        string blockHash           = string.Empty;
                        string blockTimestampFound = "0";
                        string blockReward         = "0";
                        if (ClassApi.DictionaryBlockHashCache.ContainsKey(lastBlockFound))
                        {
                            blockHash           = ClassApi.DictionaryBlockHashCache[lastBlockFound];
                            blockTimestampFound = ClassApi.DictionaryBlockDateFoundCache[lastBlockFound];
                            blockReward         = ClassApi.DictionaryBlockRewardCache[lastBlockFound];
                        }
                        else
                        {
                            var blockResult = await ClassRemoteApi.GetBlockInformation("" + lastBlockFound);

                            if (blockResult != null)
                            {
                                JObject blockJson = JObject.Parse(blockResult);
                                blockHash           = blockJson["block_hash"].ToString();
                                blockTimestampFound = blockJson["block_timestamp_found"].ToString();
                                blockReward         = blockJson["block_reward"].ToString();
                                try
                                {
                                    ClassApi.DictionaryBlockHashCache.Add(lastBlockFound, blockHash);
                                }
                                catch
                                {
                                }
                                try
                                {
                                    ClassApi.DictionaryBlockDateFoundCache.Add(lastBlockFound, blockTimestampFound);
                                }
                                catch
                                {
                                }
                                try
                                {
                                    ClassApi.DictionaryBlockRewardCache.Add(lastBlockFound, blockReward);
                                }
                                catch
                                {
                                }
                            }
                            else
                            {
                                ClassLog.ConsoleWriteLog("Pool API - Warning, your Remote Node HTTP API seems to not respond !", ClassLogEnumeration.IndexPoolApiErrorLog, ClassLogConsoleEnumeration.IndexPoolConsoleRedLog, true);
                                await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                            }
                        }
                        string miningPortInfo = string.Empty;
                        if (MiningPoolSetting.MiningPoolMiningPort.Count > 0)
                        {
                            int counter = 0;
                            foreach (var miningPort in MiningPoolSetting.MiningPoolMiningPort)
                            {
                                counter++;
                                if (counter < MiningPoolSetting.MiningPoolMiningPort.Count)
                                {
                                    miningPortInfo += miningPort.Key + "|" + miningPort.Value + ";";     // Mining port + mining difficulty;
                                }
                                else
                                {
                                    miningPortInfo += miningPort.Key + "|" + miningPort.Value;     // Mining port + mining difficulty;
                                }
                            }
                        }
                        Dictionary <string, string> poolStatsContent = new Dictionary <string, string>()
                        {
                            { "pool_hashrate", ClassMiningPoolGlobalStats.TotalMinerHashrate.ToString() },
                            { "pool_total_miner_connected", ClassMiningPoolGlobalStats.TotalMinerConnected.ToString() },
                            { "pool_total_worker_connected", ClassMiningPoolGlobalStats.TotalWorkerConnected.ToString() },
                            { "pool_total_payment", ClassMinerStats.DictionaryPoolTransaction.Count.ToString() },
                            { "pool_total_paid", ClassMiningPoolGlobalStats.PoolTotalPaid.ToString("F" + ClassConnectorSetting.MaxDecimalPlace) },
                            { "pool_total_block_found", ClassMiningPoolGlobalStats.ListBlockFound.Count.ToString() },
                            { "pool_fee", MiningPoolSetting.MiningPoolFee.ToString() },
                            { "pool_last_block_found_date", lastBlockFoundDate },
                            { "pool_mining_port_and_difficulty", miningPortInfo },
                            { "pool_minimum_payment", "" + MiningPoolSetting.MiningPoolMinimumBalancePayment },
                            { "network_height", ClassMiningPoolGlobalStats.CurrentBlockId },
                            { "network_difficulty", ClassMiningPoolGlobalStats.CurrentBlockDifficulty },
                            { "network_hashrate", networkHashrate.ToString() },
                            { "network_last_block_hash", blockHash },
                            { "network_last_block_found_timestamp", blockTimestampFound },
                            { "network_last_block_reward", blockReward }
                        };
                        await BuildAndSendHttpPacketAsync(string.Empty, true, poolStatsContent);
                    }
                    else
                    {
                        ClassLog.ConsoleWriteLog("Pool API - Warning, your Remote Node HTTP API seems to not respond !", ClassLogEnumeration.IndexPoolApiErrorLog, ClassLogConsoleEnumeration.IndexPoolConsoleRedLog, true);
                        await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketError);
                    }
                    break;

                default:
                    await BuildAndSendHttpPacketAsync(ClassApiEnumeration.PacketNotExist);

                    break;
                }
            }
        }