예제 #1
0
        private static async Task <string> ProceedHttpRequest(string url, string requestString)
        {
            string result = string.Empty;

            if (MiningPoolSetting.MiningPoolRpcWalletUseEncryptionKey)
            {
                requestString = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, requestString, MiningPoolSetting.MiningPoolRpcWalletEncryptionKey, ClassWalletNetworkSetting.KeySize);
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + requestString);

            request.AutomaticDecompression         = DecompressionMethods.GZip;
            request.ServicePoint.Expect100Continue = false;
            request.KeepAlive = false;
            request.Timeout   = 10000;
            request.UserAgent = ClassConnectorSetting.CoinName + " Mining Pool Tool - " + Assembly.GetExecutingAssembly().GetName().Version + "R";
            string responseContent = string.Empty;

            using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        result = await reader.ReadToEndAsync();
                    }
            if (MiningPoolSetting.MiningPoolRpcWalletUseEncryptionKey)
            {
                result = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, result, MiningPoolSetting.MiningPoolRpcWalletEncryptionKey, ClassWalletNetworkSetting.KeySize);
            }
            return(result);
        }
예제 #2
0
        /// <summary>
        /// Get wallet token from token system.
        /// </summary>
        /// <param name="getSeedNodeRandom"></param>
        /// <param name="walletAddress"></param>
        /// <returns></returns>
        private static async Task <string> GetWalletTokenAsync(string getSeedNodeRandom, string walletAddress)
        {
            string encryptedRequest = ClassRpcWalletCommand.TokenAsk + "|empty-token|" + (DateTimeOffset.Now.ToUnixTimeSeconds() + 1);

            encryptedRequest = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, encryptedRequest, walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey(), ClassWalletNetworkSetting.KeySize);
            string responseWallet = await ProceedTokenRequestAsync("http://" + getSeedNodeRandom + ":" + ClassConnectorSetting.SeedNodeTokenPort + "/" + ClassConnectorSettingEnumeration.WalletTokenType + "|" + walletAddress + "|" + encryptedRequest);

            var responseWalletJson = JObject.Parse(responseWallet);

            responseWallet = responseWalletJson["result"].ToString();
            responseWallet = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, responseWallet, walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey(), ClassWalletNetworkSetting.KeySize);
            var splitResponseWallet = responseWallet.Split(new[] { "|" }, StringSplitOptions.None);

            if ((long.Parse(splitResponseWallet[splitResponseWallet.Length - 1]) + 10) - DateTimeOffset.Now.ToUnixTimeSeconds() < 60)
            {
                if (long.Parse(splitResponseWallet[splitResponseWallet.Length - 1]) + 10 >= DateTimeOffset.Now.ToUnixTimeSeconds())
                {
                    return(splitResponseWallet[1]);
                }
                else
                {
                    return(RpcTokenNetworkNotExist);
                }
            }
            else
            {
                return(RpcTokenNetworkNotExist);
            }
        }
예제 #3
0
 /// <summary>
 /// Initialize sync database.
 /// </summary>
 /// <returns></returns>
 public static bool InitializeSyncDatabase()
 {
     try
     {
         if (!File.Exists(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile)))
         {
             File.Create(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile)).Close();
         }
         else
         {
             using (FileStream fs = File.Open(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
             {
                 using (BufferedStream bs = new BufferedStream(fs))
                 {
                     using (StreamReader sr = new StreamReader(bs))
                     {
                         string line;
                         int    lineRead = 0;
                         while ((line = sr.ReadLine()) != null)
                         {
                             lineRead++;
                             if (line.Contains(ClassSyncDatabaseEnumeration.DatabaseSyncStartLine))
                             {
                                 string transactionLine      = line.Replace(ClassSyncDatabaseEnumeration.DatabaseSyncStartLine, "");
                                 var    splitTransactionLine = transactionLine.Split(new[] { "|" }, StringSplitOptions.None);
                                 string walletAddress        = splitTransactionLine[0];
                                 if (ClassRpcDatabase.RpcDatabaseContent.ContainsKey(walletAddress))
                                 {
                                     string transaction      = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, splitTransactionLine[1], walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey(), ClassWalletNetworkSetting.KeySize);
                                     var    splitTransaction = transaction.Split(new[] { "#" }, StringSplitOptions.None);
                                     if (splitTransaction[0] == "anonymous")
                                     {
                                         ClassRpcDatabase.RpcDatabaseContent[walletAddress].InsertWalletTransactionSync(transaction, true, false);
                                     }
                                     else
                                     {
                                         ClassRpcDatabase.RpcDatabaseContent[walletAddress].InsertWalletTransactionSync(transaction, false, false);
                                     }
                                     TotalTransactionRead++;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     catch
     {
         return(false);
     }
     SyncDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(System.AppDomain.CurrentDomain.BaseDirectory + SyncDatabaseFile), true, Encoding.UTF8, 8192)
     {
         AutoFlush = true
     };
     ClassConsole.ConsoleWriteLine("Total transaction read from sync database: " + TotalTransactionRead, ClassConsoleColorEnumeration.IndexConsoleGreenLog, ClassConsoleLogLevelEnumeration.LogLevelSyncDatabase);
     return(true);
 }
예제 #4
0
        /// <summary>
        /// Update wallet balance from token system.
        /// </summary>
        /// <param name="token"></param>
        /// <param name="getSeedNodeRandom"></param>
        /// <param name="walletAddress"></param>
        public static async Task <bool> GetWalletBalanceTokenAsync(string getSeedNodeRandom, string walletAddress)
        {
            string token = await GetWalletTokenAsync(getSeedNodeRandom, walletAddress);

            if (token != RpcTokenNetworkNotExist)
            {
                string encryptedRequest = ClassRpcWalletCommand.TokenAskBalance + "|" + token + "|" + (DateTimeOffset.Now.ToUnixTimeSeconds() + 1);
                encryptedRequest = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, encryptedRequest, walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey(), ClassWalletNetworkSetting.KeySize);
                string responseWallet = await ProceedTokenRequestAsync("http://" + getSeedNodeRandom + ":" + ClassConnectorSetting.SeedNodeTokenPort + "/" + ClassConnectorSettingEnumeration.WalletTokenType + "|" + walletAddress + "|" + encryptedRequest);

                var responseWalletJson = JObject.Parse(responseWallet);
                responseWallet = responseWalletJson["result"].ToString();
                if (responseWallet != RpcTokenNetworkNotExist)
                {
                    responseWallet = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, responseWallet, walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey() + token, ClassWalletNetworkSetting.KeySize);
                    if (responseWallet != ClassAlgoErrorEnumeration.AlgoError)
                    {
                        string walletBalance      = responseWallet;
                        var    splitWalletBalance = walletBalance.Split(new[] { "|" }, StringSplitOptions.None);
                        if ((long.Parse(splitWalletBalance[splitWalletBalance.Length - 1]) + 10) - DateTimeOffset.Now.ToUnixTimeSeconds() < 60)
                        {
                            if (long.Parse(splitWalletBalance[splitWalletBalance.Length - 1]) + 10 >= DateTimeOffset.Now.ToUnixTimeSeconds())
                            {
                                ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletBalance(splitWalletBalance[1]);
                                ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletPendingBalance(splitWalletBalance[2]);
                                ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletUniqueId(splitWalletBalance[3]);
                                ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletAnonymousUniqueId(splitWalletBalance[4]);
                                return(true);
                            }
                            else
                            {
                                ClassConsole.ConsoleWriteLine("Wallet packet time balance token request: " + walletBalance + " is expired.", ClassConsoleColorEnumeration.IndexConsoleRedLog, ClassConsoleLogLevelEnumeration.LogLevelWalletObject);
                            }
                        }
                        else
                        {
                            ClassConsole.ConsoleWriteLine("Wallet packet time balance token request: " + walletBalance + " is too huge", ClassConsoleColorEnumeration.IndexConsoleRedLog, ClassConsoleLogLevelEnumeration.LogLevelWalletObject);
                        }
                    }
                }
            }
            return(false);
        }
예제 #5
0
        /// <summary>
        /// Decrypt and sorting a transaction received on sync, finaly save it.
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="walletAddress"></param>
        /// <param name="walletPublicKey"></param>
        /// <returns></returns>
        public static void SaveTransactionSorted(string transaction, string walletAddress, string walletPublicKey, bool anonymous)
        {
            var    splitTransaction  = transaction.Split(new[] { "#" }, StringSplitOptions.None);
            string type              = splitTransaction[0];
            string timestamp         = splitTransaction[3];
            string hashTransaction   = splitTransaction[4];
            string timestampReceived = splitTransaction[5];
            string blockchainHeight  = splitTransaction[6];
            string realTransactionInformationSenderSide   = splitTransaction[7];
            string realTransactionInformationReceiverSide = splitTransaction[8];

            string realTransactionInformationDecrypted = "NULL";

            if (type == "SEND")
            {
                realTransactionInformationDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, realTransactionInformationSenderSide, walletAddress + walletPublicKey, ClassWalletNetworkSetting.KeySize);
            }
            else if (type == "RECV")
            {
                realTransactionInformationDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, realTransactionInformationReceiverSide, walletAddress + walletPublicKey, ClassWalletNetworkSetting.KeySize);
            }
            if (realTransactionInformationDecrypted != "NULL" && realTransactionInformationDecrypted != ClassAlgoErrorEnumeration.AlgoError)
            {
                var    splitDecryptedTransactionInformation = realTransactionInformationDecrypted.Split(new[] { "-" }, StringSplitOptions.None);
                string amountTransaction     = splitDecryptedTransactionInformation[0];
                string feeTransaction        = splitDecryptedTransactionInformation[1];
                string walletAddressDstOrSrc = splitDecryptedTransactionInformation[2];
                string finalTransaction      = string.Empty;
                if (anonymous)
                {
                    finalTransaction = "anonymous#" + type + "#" + hashTransaction + "#" + walletAddressDstOrSrc + "#" + amountTransaction + "#" + feeTransaction + "#" + timestamp + "#" + timestampReceived + "#" + blockchainHeight;
                    ClassRpcDatabase.RpcDatabaseContent[walletAddress].InsertWalletTransactionSync(finalTransaction, true, true);
                }
                else
                {
                    finalTransaction = "normal#" + type + "#" + hashTransaction + "#" + walletAddressDstOrSrc + "#" + amountTransaction + "#" + feeTransaction + "#" + timestamp + "#" + timestampReceived + "#" + blockchainHeight;
                    ClassRpcDatabase.RpcDatabaseContent[walletAddress].InsertWalletTransactionSync(finalTransaction, false, true);
                }
            }
        }
        /// <summary>
        ///     Add transaction to the list.
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="node"></param>
        public static async Task AddWalletTransactionAsync(string transaction, string node)
        {
#if DEBUG
            Log.WriteLine("Wallet transaction history received: " + transaction
                          .Replace(
                              ClassRemoteNodeCommandForWallet.RemoteNodeRecvPacketEnumeration
                              .WalletTransactionPerId, ""));
#endif
            bool errorSyncTransaction = false;

            if (!OnLoad)
            {
                var splitTransaction = transaction
                                       .Replace(ClassRemoteNodeCommandForWallet.RemoteNodeRecvPacketEnumeration.WalletTransactionPerId,
                                                string.Empty).Split(new[] { "#" }, StringSplitOptions.None);
                var hashTransaction = splitTransaction[4]; // Transaction Hash.
                if (!ListTransaction.ContainsKey(hashTransaction))
                {
                    var type              = splitTransaction[0];
                    var timestamp         = splitTransaction[3]; // Timestamp Send CEST.
                    var realFeeAmountSend = splitTransaction[7]; // Real fee and amount crypted for sender.
                    var realFeeAmountRecv = splitTransaction[8]; // Real fee and amount crypted for sender.

                    var amountAndFeeDecrypted = ClassAlgoErrorEnumeration.AlgoError;
                    if (type == "SEND")
                    {
                        amountAndFeeDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                                   realFeeAmountSend,
                                                                                   Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                                                                   Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey,
                                                                                   ClassWalletNetworkSetting.KeySize); // AES
                    }
                    else if (type == "RECV")
                    {
                        amountAndFeeDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                                   realFeeAmountRecv,
                                                                                   Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                                                                   Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey,
                                                                                   ClassWalletNetworkSetting.KeySize); // AES
                    }
                    if (amountAndFeeDecrypted != ClassAlgoErrorEnumeration.AlgoError)
                    {
                        var splitDecryptedAmountAndFee =
                            amountAndFeeDecrypted.Split(new[] { "-" }, StringSplitOptions.None);
                        var amountDecrypted = splitDecryptedAmountAndFee[0];
                        var feeDecrypted    = splitDecryptedAmountAndFee[1];
                        var walletDstOrSrc  = splitDecryptedAmountAndFee[2];


                        var timestampRecv    = splitTransaction[5]; // Timestamp Recv CEST.
                        var blockchainHeight = splitTransaction[6]; // Blockchain height.

                        var finalTransaction = type + "#" + hashTransaction + "#" + walletDstOrSrc + "#" +
                                               amountDecrypted + "#" + feeDecrypted + "#" + timestamp + "#" +
                                               timestampRecv + "#" + blockchainHeight;

                        var finalTransactionEncrypted = ClassAlgo.GetEncryptedResultManual(
                            ClassAlgoEnumeration.Rijndael, finalTransaction,
                            Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                            Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey,
                            ClassWalletNetworkSetting.KeySize);                               // AES

                        if (finalTransactionEncrypted == ClassAlgoErrorEnumeration.AlgoError) // Ban bad remote node.
                        {
                            errorSyncTransaction = true;
                        }
                        else
                        {
                            var splitBlockchainHeight = blockchainHeight.Split(new[] { "~" }, StringSplitOptions.None);

                            var transactionObject = new ClassWalletTransactionObject
                            {
                                TransactionType          = type,
                                TransactionHash          = hashTransaction,
                                TransactionWalletAddress = walletDstOrSrc,
                                TransactionAmount        = decimal.Parse(amountDecrypted.ToString(Program.GlobalCultureInfo),
                                                                         NumberStyles.Currency, Program.GlobalCultureInfo),
                                TransactionFee = decimal.Parse(feeDecrypted.ToString(Program.GlobalCultureInfo),
                                                               NumberStyles.Currency, Program.GlobalCultureInfo),
                                TransactionTimestampSend    = long.Parse(timestamp),
                                TransactionTimestampRecv    = long.Parse(timestampRecv),
                                TransactionBlockchainHeight = splitBlockchainHeight[0].Replace("{", "")
                            };

                            ListTransaction.Add(hashTransaction, transactionObject);


                            await SaveWalletCache(Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress, finalTransactionEncrypted);

#if DEBUG
                            Log.WriteLine("Total transactions downloaded: " +
                                          ListTransaction.Count + "/" +
                                          Program.WalletXiropht.ClassWalletObject.TotalTransactionInSync + ".");
#endif
                        }
                    }
                    else
                    {
#if DEBUG
                        Log.WriteLine("Can't decrypt transaction: " + transaction + " result: " +
                                      amountAndFeeDecrypted);
#endif
                        errorSyncTransaction = true;
                    }
                }
                else
                {
#if DEBUG
                    Log.WriteLine("Wallet transaction hash: " + hashTransaction + " already exist on database.");
#endif
                    errorSyncTransaction = true;
                }
            }

            if (errorSyncTransaction)
            {
                if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(node))
                {
                    if (!Program.WalletXiropht.ClassWalletObject.ListRemoteNodeBanned.ContainsKey(node))
                    {
                        Program.WalletXiropht.ClassWalletObject.ListRemoteNodeBanned.Add(node,
                                                                                         ClassUtils.DateUnixTimeNowSecond());
                        ClassPeerList.IncrementPeerDisconnect(node);
                    }
                    else
                    {
                        Program.WalletXiropht.ClassWalletObject.ListRemoteNodeBanned[node] =
                            ClassUtils.DateUnixTimeNowSecond();
                        ClassPeerList.IncrementPeerDisconnect(node);
                    }
                }


                await Program.WalletXiropht.ClassWalletObject.DisconnectRemoteNodeTokenSync();

                Program.WalletXiropht.ClassWalletObject.WalletOnUseSync = false;
            }

            Program.WalletXiropht.ClassWalletObject.InReceiveTransaction = false;
        }
예제 #7
0
        /// <summary>
        /// Handle packet wallet received from the blockchain network.
        /// </summary>
        /// <param name="packet"></param>
        private void HandlePacketBlockchainNetworkWallet(string packet)
        {
            var splitPacket = packet.Split(new[] { "|" }, StringSplitOptions.None);

            switch (splitPacket[0])
            {
            case ClassWalletCommand.ClassWalletReceiveEnumeration.WaitingCreatePhase:
                //ClassConsole.ConsoleWriteLine("Please wait a moment, your wallet pending creation..", ClassConsoleEnumeration.IndexConsoleYellowLog);
                break;

            case ClassWalletCommand.ClassWalletReceiveEnumeration.WalletCreatePasswordNeedLetters:
            case ClassWalletCommand.ClassWalletReceiveEnumeration.WalletCreatePasswordNeedMoreCharacters:
                WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorError;
                FullDisconnection();
                break;

            case ClassWalletCommand.ClassWalletReceiveEnumeration.CreatePhase:
                if (splitPacket[1] == ClassAlgoErrorEnumeration.AlgoError)
                {
                    WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorError;
                    FullDisconnection();
                }
                else
                {
                    var decryptWalletDataCreate = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, splitPacket[1], WalletPassword, ClassWalletNetworkSetting.KeySize);
                    if (decryptWalletDataCreate == ClassAlgoErrorEnumeration.AlgoError)
                    {
                        WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorError;
                        FullDisconnection();
                    }
                    else
                    {
                        string walletDataCreate             = ClassUtils.DecompressData(decryptWalletDataCreate);
                        var    splitDecryptWalletDataCreate = walletDataCreate.Split(new[] { "\n" }, StringSplitOptions.None);
                        var    pinWallet     = splitPacket[2];
                        var    walletAddress = splitDecryptWalletDataCreate[0];
                        var    publicKey     = splitDecryptWalletDataCreate[2];
                        var    privateKey    = splitDecryptWalletDataCreate[3];
                        WalletAddressResult = walletAddress;
                        ClassRpcDatabase.InsertNewWalletAsync(walletAddress, publicKey, privateKey, pinWallet, WalletPassword);
                        WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorSuccess;
                        FullDisconnection();
                    }
                }
                break;

            case ClassWalletCommand.ClassWalletReceiveEnumeration.WalletAskSuccess:
                string walletDataCreation = splitPacket[1];

                if (walletDataCreation == ClassAlgoErrorEnumeration.AlgoError)
                {
                    ClassConsole.ConsoleWriteLine("Restoring wallet failed, please try again later.", ClassConsoleColorEnumeration.IndexConsoleRedLog);
                    WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorError;
                    FullDisconnection();
                }
                else
                {
                    var decryptWalletDataCreation = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, walletDataCreation, WalletPrivateKey, ClassWalletNetworkSetting.KeySize);
                    if (decryptWalletDataCreation == ClassAlgoErrorEnumeration.AlgoError)
                    {
                        ClassConsole.ConsoleWriteLine("Restoring wallet failed, please try again later.", ClassConsoleColorEnumeration.IndexConsoleRedLog);
                        WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorError;
                        FullDisconnection();
                    }
                    else
                    {
                        var splitWalletData = decryptWalletDataCreation.Split(new[] { "\n" }, StringSplitOptions.None);
                        var publicKey       = splitWalletData[2];
                        var privateKey      = splitWalletData[3];
                        var pinCode         = splitWalletData[4];
                        if (ClassRpcDatabase.RpcDatabaseContent.ContainsKey(WalletAddress))
                        {
                            ClassRpcDatabase.RpcDatabaseContent[WalletAddress].SetWalletAddress(WalletAddress);
                            ClassRpcDatabase.RpcDatabaseContent[WalletAddress].SetWalletPublicKey(publicKey);
                            ClassRpcDatabase.RpcDatabaseContent[WalletAddress].SetWalletPrivateKey(privateKey);
                            ClassRpcDatabase.RpcDatabaseContent[WalletAddress].SetWalletPinCode(pinCode);
                            WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorSuccess;
                            FullDisconnection();
                        }
                        else
                        {
                            ClassConsole.ConsoleWriteLine("Restoring wallet failed, wallet address: " + WalletAddress + " not exist inside database, please try again later.", ClassConsoleColorEnumeration.IndexConsoleRedLog);
                            WalletCreateResult = ClassWalletCreatorEnumeration.WalletCreatorError;
                            FullDisconnection();
                        }
                    }
                }
                break;
            }
        }
예제 #8
0
        /// <summary>
        ///     Open and connect the wallet.
        /// </summary>
        /// <returns></returns>
        private void OpenAndConnectWallet()
        {
            if (textBoxPasswordWallet.Text == "")
            {
#if WINDOWS
                ClassFormPhase.MessageBoxInterface(
                    ClassTranslation.GetLanguageTextFromOrder(
                        "OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_CONTENT_TEXT"),
                    ClassTranslation.GetLanguageTextFromOrder(
                        "OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
#else
                MessageBox.Show(Program.WalletXiropht, ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_CONTENT_TEXT"),
                                ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
#endif
                return;
            }

            if (Program.WalletXiropht.WalletEnableProxyMode)
            {
                if (!Program.WalletXiropht.EnableTokenNetworkMode)
                {
#if WINDOWS
                    if (MetroMessageBox.Show(Program.WalletXiropht,
                                             "The proxy mode option is enabled, default mode to connect is recommended, also the proxy mode check process on initialization can take time. Do you want to continue ?",
                                             "Proxy feature", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) ==
                        DialogResult.No)
                    {
                        Program.WalletXiropht.ClassWalletObject.FullDisconnection(true, true).ConfigureAwait(false);
                        return;
                    }
#else
                    if (MessageBox.Show(Program.WalletXiropht,
                                        "The proxy mode option is enabled, default mode to connect is recommended, also the proxy mode check process on initialization can take time. Do you want to continue ?",
                                        "Proxy feature", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) ==
                        DialogResult.No)
                    {
                        Program.WalletXiropht.ClassWalletObject.FullDisconnection(true, true).ConfigureAwait(false);
                        return;
                    }
#endif
                }
            }

            Task.Factory.StartNew(async delegate
            {
                await Program.WalletXiropht.InitializationWalletObject();
                try
                {
                    var error = false;

                    var passwordEncrypted = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                               textBoxPasswordWallet.Text, textBoxPasswordWallet.Text, ClassWalletNetworkSetting.KeySize);

                    if (Program.WalletXiropht.ClassWalletObject != null)
                    {
                        Program.WalletXiropht.ClassWalletObject.WalletDataDecrypted =
                            ClassAlgo.GetDecryptedResultManual(
                                ClassAlgoEnumeration.Rijndael,
                                _walletFileData, passwordEncrypted, ClassWalletNetworkSetting.KeySize); // AES
                        if (Program.WalletXiropht.ClassWalletObject.WalletDataDecrypted ==
                            ClassAlgoErrorEnumeration.AlgoError)
                        {
                            error = true;
                        }

                        if (error)
                        {
                            Program.WalletXiropht.ClassWalletObject.WalletDataDecrypted =
                                ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                   _walletFileData, textBoxPasswordWallet.Text,
                                                                   ClassWalletNetworkSetting.KeySize); // AES
                        }
                        if (Program.WalletXiropht.ClassWalletObject.WalletDataDecrypted ==
                            ClassAlgoErrorEnumeration.AlgoError)
                        {
#if WINDOWS
                            ClassFormPhase.MessageBoxInterface(
                                ClassTranslation.GetLanguageTextFromOrder(
                                    "OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                                ClassTranslation.GetLanguageTextFromOrder(
                                    "OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_TITLE_TEXT"),
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
#else
                            MessageBox.Show(Program.WalletXiropht,
                                            ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                                            ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
                            return;
                        }

                        var splitWalletFileDecrypted =
                            Program.WalletXiropht.ClassWalletObject.WalletDataDecrypted.Split(new[] { "\n" },
                                                                                              StringSplitOptions.None);
                        var walletAddress = splitWalletFileDecrypted[0];
                        var walletKey     = splitWalletFileDecrypted[1];

                        if (Program.WalletXiropht.ClassWalletObject == null)
                        {
                            await Program.WalletXiropht.InitializationWalletObject();
                        }
                        if (!Program.WalletXiropht.EnableTokenNetworkMode)
                        {
                            if (!await Program.WalletXiropht.ClassWalletObject.InitializationWalletConnection(
                                    walletAddress,
                                    textBoxPasswordWallet.Text,
                                    walletKey, ClassWalletPhase.Login))
                            {
                                MethodInvoker invoker = () => textBoxPasswordWallet.Text = "";
                                BeginInvoke(invoker);
#if WINDOWS
                                ClassFormPhase.MessageBoxInterface(
                                    ClassTranslation.GetLanguageTextFromOrder(
                                        "OPEN_WALLET_ERROR_MESSAGE_NETWORK_CONTENT_TEXT"),
                                    ClassTranslation.GetLanguageTextFromOrder(
                                        "OPEN_WALLET_ERROR_MESSAGE_NETWORK_TITLE_TEXT"), MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
#else
                                MessageBox.Show(Program.WalletXiropht,
                                                ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_CONTENT_TEXT"), ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_TITLE_TEXT"), MessageBoxButtons.OK,
                                                MessageBoxIcon.Warning);
#endif
                                await Program.WalletXiropht.ClassWalletObject.FullDisconnection(true, true);
                                return;
                            }

                            MethodInvoker invoke = () => textBoxPasswordWallet.Text = "";
                            BeginInvoke(invoke);

                            Program.WalletXiropht.ClassWalletObject.ListenSeedNodeNetworkForWallet();

                            _walletFileData   = string.Empty;
                            _fileSelectedPath = string.Empty;
                            invoke            = () =>
                                                labelOpenFileSelected.Text =
                                ClassTranslation.GetLanguageTextFromOrder(
                                    "OPEN_WALLET_LABEL_FILE_SELECTED_TEXT");
                            BeginInvoke(invoke);

                            if (Program.WalletXiropht.WalletSyncMode == ClassWalletSyncMode.WALLET_SYNC_DEFAULT || !Program.WalletXiropht.WalletEnableProxyMode)
                            {
                                if (await Program.WalletXiropht.ClassWalletObject.WalletConnect.SendPacketWallet(
                                        Program.WalletXiropht.ClassWalletObject.Certificate, string.Empty, false))
                                {
                                    await Program.WalletXiropht.ClassWalletObject.WalletConnect.SendPacketWallet(
                                        ClassConnectorSettingEnumeration.WalletLoginType + ClassConnectorSetting.PacketContentSeperator + Program.WalletXiropht
                                        .ClassWalletObject.WalletConnect.WalletAddress,
                                        Program.WalletXiropht.ClassWalletObject.Certificate, true);
                                }
                            }
                            else if (Program.WalletXiropht.WalletSyncMode ==
                                     ClassWalletSyncMode.WALLET_SYNC_PUBLIC_NODE && Program.WalletXiropht.WalletEnableProxyMode)
                            {
                                if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(Program.WalletXiropht
                                                                                  .ClassWalletObject.SeedNodeConnectorWallet.ReturnCurrentSeedNodeHost()))
                                {
                                    await Program.WalletXiropht.ClassWalletObject.SeedNodeConnectorWallet.SendPacketToSeedNodeAsync(
                                        ClassConnectorSettingEnumeration.WalletLoginProxy +
                                        ClassConnectorSetting.PacketContentSeperator +
                                        Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                        ClassConnectorSetting.PacketContentSeperator +
                                        Program.WalletXiropht.ClassWalletObject.Certificate + ClassConnectorSetting.PacketSplitSeperator, string.Empty, false, false);
                                }
                                else
                                {
                                    if (await Program.WalletXiropht.ClassWalletObject.WalletConnect.SendPacketWallet(
                                            Program.WalletXiropht.ClassWalletObject.Certificate, string.Empty, false))
                                    {
                                        await Program.WalletXiropht.ClassWalletObject.WalletConnect.SendPacketWallet(
                                            ClassConnectorSettingEnumeration.WalletLoginType + ClassConnectorSetting.PacketContentSeperator + Program.WalletXiropht
                                            .ClassWalletObject.WalletConnect.WalletAddress,
                                            Program.WalletXiropht.ClassWalletObject.Certificate, true);
                                    }
                                }
                            }
                            else if (Program.WalletXiropht.WalletSyncMode ==
                                     ClassWalletSyncMode.WALLET_SYNC_MANUAL_NODE && Program.WalletXiropht.WalletEnableProxyMode)
                            {
                                await Program.WalletXiropht.ClassWalletObject.SeedNodeConnectorWallet.SendPacketToSeedNodeAsync(
                                    ClassConnectorSettingEnumeration.WalletLoginProxy +
                                    ClassConnectorSetting.PacketContentSeperator +
                                    Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                    ClassConnectorSetting.PacketContentSeperator +
                                    Program.WalletXiropht.ClassWalletObject.Certificate + ClassConnectorSetting.PacketSplitSeperator, string.Empty, false, false);
                            }
                        }
                        else
                        {
                            Program.WalletXiropht.ClassWalletObject.InitializationWalletTokenMode(walletAddress,
                                                                                                  walletKey,
                                                                                                  textBoxPasswordWallet.Text);
                            MethodInvoker invoke = () => textBoxPasswordWallet.Text = "";
                            BeginInvoke(invoke);
                            invoke = () =>
                                     labelOpenFileSelected.Text =
                                ClassTranslation.GetLanguageTextFromOrder(
                                    "OPEN_WALLET_LABEL_FILE_SELECTED_TEXT");
                            BeginInvoke(invoke);
                            ClassFormPhase.SwitchFormPhase(ClassFormPhaseEnumeration.Overview);
                        }
                    }
                    else
                    {
#if WINDOWS
                        ClassFormPhase.MessageBoxInterface(
                            ClassTranslation.GetLanguageTextFromOrder(
                                "OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                            ClassTranslation.GetLanguageTextFromOrder(
                                "OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_TITLE_TEXT"),
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
                        MessageBox.Show(Program.WalletXiropht,
                                        ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                                        ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
                    }
                }
                catch
                {
#if WINDOWS
                    ClassFormPhase.MessageBoxInterface(
                        ClassTranslation.GetLanguageTextFromOrder(
                            "OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                        ClassTranslation.GetLanguageTextFromOrder(
                            "OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_TITLE_TEXT"),
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
                    MessageBox.Show(Program.WalletXiropht,
                                    ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                                    ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
                }
            }, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Current);
        }
예제 #9
0
        /// <summary>
        /// Generate QR Code from private key + password, encrypt the QR Code bitmap with the private key, build the request to be send on the blockchain.
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string GenerateQRCodeKeyEncryptedRepresentation(string privateKey, string password)
        {
            try
            {
                QrCodeEncodingOptions options = new QrCodeEncodingOptions
                {
                    DisableECI   = true,
                    CharacterSet = "UTF-8",
                    Width        = 2,
                    Height       = 2,
                };

                BarcodeWriter qr = new BarcodeWriter
                {
                    Options = options,
                    Format  = BarcodeFormat.QR_CODE
                };
                string sourceKey = privateKey.Trim() + "|" + password.Trim() + "|" + ClassUtils.DateUnixTimeNowSecond();
                using (var representationQRCode = new Bitmap(qr.Write(sourceKey)))
                {
                    LuminanceSource source = new BitmapLuminanceSource(representationQRCode);

                    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                    Result       result = new MultiFormatReader().decode(bitmap);

                    if (result != null)
                    {
                        if (result.Text == sourceKey)
                        {
                            string qrCodeString           = BitmapToBase64String(representationQRCode);
                            string QrCodeStringEncrypted  = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, qrCodeString, privateKey, ClassWalletNetworkSetting.KeySize);
                            string qrCodeEncryptedRequest = string.Empty;

                            if (privateKey.Contains("$"))
                            {
                                long walletUniqueIdInstance = long.Parse(privateKey.Split(new[] { "$" }, StringSplitOptions.None)[1]);
                                qrCodeEncryptedRequest = walletUniqueIdInstance + "|" + QrCodeStringEncrypted;
                            }
                            else
                            {
                                string randomEndPrivateKey = privateKey.Remove(0, (privateKey.Length - ClassUtils.GetRandomBetween(privateKey.Length / 4, privateKey.Length / 8))); // Indicate only a small part of the end of the private key (For old private key users).
                                qrCodeEncryptedRequest = randomEndPrivateKey + "|" + QrCodeStringEncrypted;
                            }

                            // Testing QR Code encryption.
                            string decryptQrCode = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, QrCodeStringEncrypted, privateKey, ClassWalletNetworkSetting.KeySize); // Decrypt QR Code.

                            using (Bitmap qrCode = Base64StringToBitmap(decryptQrCode))                                                                                                     // Retrieve data to bitmap.
                            {
                                source = new BitmapLuminanceSource(qrCode);

                                bitmap = new BinaryBitmap(new HybridBinarizer(source));
                                result = new MultiFormatReader().decode(bitmap);

                                if (result != null)
                                {
                                    if (result.Text == sourceKey)       // Check representation.
                                    {
                                        return(qrCodeEncryptedRequest); // Return encrypted QR Code.
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception error)
            {
#if DEBUG
                Console.WriteLine("error: " + error.Message);
#endif
            }
            return(null);
        }
예제 #10
0
 /// <summary>
 /// Load RPC Database file.
 /// </summary>
 /// <returns></returns>
 public static bool LoadRpcDatabaseFile()
 {
     RpcDatabaseContent = new Dictionary <string, ClassWalletObject>();
     try
     {
         if (File.Exists(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile)))
         {
             using (FileStream fs = File.Open(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
             {
                 using (BufferedStream bs = new BufferedStream(fs))
                 {
                     using (StreamReader sr = new StreamReader(bs))
                     {
                         string line;
                         int    lineRead = 0;
                         while ((line = sr.ReadLine()) != null)
                         {
                             lineRead++;
                             if (line.StartsWith(ClassRpcDatabaseEnumeration.DatabaseWalletStartLine))
                             {
                                 string walletData = line.Replace(ClassRpcDatabaseEnumeration.DatabaseWalletStartLine, "");
                                 walletData = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, walletData, RpcDatabasePassword, ClassWalletNetworkSetting.KeySize);
                                 if (walletData != ClassAlgoErrorEnumeration.AlgoError)
                                 {
                                     var splitWalletData = walletData.Split(new[] { "|" }, StringSplitOptions.None);
                                     var walletAddress   = splitWalletData[0];
                                     if (!RpcDatabaseContent.ContainsKey(walletAddress))
                                     {
                                         var walletPublicKey  = splitWalletData[1];
                                         var walletPrivateKey = splitWalletData[2];
                                         var walletPinCode    = splitWalletData[3];
                                         var walletPassword   = splitWalletData[4];
                                         var walletObject     = new ClassWalletObject(walletAddress, walletPublicKey, walletPassword, walletPrivateKey, walletPinCode, walletData);
                                         if (!RpcDatabaseContent.ContainsKey(walletAddress))
                                         {
                                             RpcDatabaseContent.Add(walletAddress, walletObject);
                                         }
                                     }
                                 }
                                 else
                                 {
                                     ClassConsole.ConsoleWriteLine("Decrypt database of wallets failed at line: " + lineRead);
                                     return(false);
                                 }
                             }
                         }
                     }
                 }
             }
         }
         else
         {
             File.Create(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile)).Close();
         }
     }
     catch
     {
         return(false);
     }
     RpcDatabaseStreamWriter = new StreamWriter(ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory + RpcDatabaseFile), true, Encoding.UTF8, 8192)
     {
         AutoFlush = true
     };
     return(true);
 }
예제 #11
0
        /// <summary>
        /// Add transaction to the list.
        /// </summary>
        /// <param name="transaction"></param>
        public static async Task AddWalletTransactionAsync(string transaction)
        {
            try
            {
#if DEBUG
                Log.WriteLine("Wallet transaction history received: " + transaction
                              .Replace(
                                  ClassRemoteNodeCommandForWallet.RemoteNodeRecvPacketEnumeration
                                  .WalletTransactionPerId, ""));
#endif
                var splitTransaction = transaction.Replace(
                    ClassRemoteNodeCommandForWallet.RemoteNodeRecvPacketEnumeration.WalletTransactionPerId,
                    "").Split(new[] { "#" }, StringSplitOptions.None);
                var type              = splitTransaction[0];
                var timestamp         = splitTransaction[3]; // Timestamp Send CEST.
                var hashTransaction   = splitTransaction[4]; // Transaction Hash.
                var realFeeAmountSend = splitTransaction[7]; // Real fee and amount crypted for sender.
                var realFeeAmountRecv = splitTransaction[8]; // Real fee and amount crypted for sender.


                var decryptKey =
                    ClassWalletObject.WalletConnect.WalletAddress + ClassWalletObject.WalletConnect.WalletKey;      // Wallet Address + Wallet Public Key

                var amountAndFeeDecrypted = "NULL";
                if (type == "SEND")
                {
                    amountAndFeeDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                               realFeeAmountSend, decryptKey, ClassWalletNetworkSetting.KeySize); // AES
                }
                else if (type == "RECV")
                {
                    amountAndFeeDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                               realFeeAmountRecv, decryptKey, ClassWalletNetworkSetting.KeySize); // AES
                }
                if (amountAndFeeDecrypted != "NULL" && amountAndFeeDecrypted != ClassAlgoErrorEnumeration.AlgoError)
                {
                    var splitDecryptedAmountAndFee =
                        amountAndFeeDecrypted.Split(new[] { "-" }, StringSplitOptions.None);
                    var amountDecrypted = splitDecryptedAmountAndFee[0];
                    var feeDecrypted    = splitDecryptedAmountAndFee[1];
                    var walletDstOrSrc  = splitDecryptedAmountAndFee[2];


                    var timestampRecv    = splitTransaction[5]; // Timestamp Recv CEST.
                    var blockchainHeight = splitTransaction[6]; // Blockchain height.

                    var finalTransaction = type + "#" + hashTransaction + "#" + walletDstOrSrc + "#" +
                                           amountDecrypted + "#" + feeDecrypted + "#" + timestamp + "#" +
                                           timestampRecv + "#" + blockchainHeight;

                    var finalTransactionEncrypted =
                        ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, finalTransaction,
                                                           ClassWalletObject.WalletConnect.WalletAddress + ClassWalletObject.WalletConnect.WalletKey,
                                                           ClassWalletNetworkSetting.KeySize); // AES

                    if (finalTransactionEncrypted == ClassAlgoErrorEnumeration.AlgoError)      // Ban bad remote node.
                    {
                        if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost))
                        {
                            if (!ClassWalletObject.ListRemoteNodeBanned.ContainsKey(ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost))
                            {
                                ClassWalletObject.ListRemoteNodeBanned.Add(ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost, ClassUtils.DateUnixTimeNowSecond());
                            }
                            else
                            {
                                ClassWalletObject.ListRemoteNodeBanned[ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost] = ClassUtils.DateUnixTimeNowSecond();
                            }
                        }
                        ClassWalletObject.DisconnectWholeRemoteNodeSyncAsync(true, true);
                    }
                    else
                    {
                        var existTransaction = false;

                        if (ListTransaction.ContainsValue(finalTransactionEncrypted))
                        {
                            existTransaction = true;
                        }

                        if (!existTransaction)
                        {
                            ListTransaction.Add(ListTransaction.Count, finalTransactionEncrypted);


                            await SaveWalletCache(ClassWalletObject.WalletConnect.WalletAddress, finalTransactionEncrypted, false);

#if DEBUG
                            Log.WriteLine("Total transactions downloaded: " +
                                          ListTransaction.Count + "/" +
                                          ClassWalletObject.TotalTransactionInSync + ".");
#endif
                        }
                    }
                }
                else
                {
#if DEBUG
                    Log.WriteLine("Can't decrypt transaction: " + transaction + " result: " +
                                  amountAndFeeDecrypted);
#endif
                    if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost))
                    {
                        if (!ClassWalletObject.ListRemoteNodeBanned.ContainsKey(ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost))
                        {
                            ClassWalletObject.ListRemoteNodeBanned.Add(ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost, ClassUtils.DateUnixTimeNowSecond());
                        }
                        else
                        {
                            ClassWalletObject.ListRemoteNodeBanned[ClassWalletObject.ListWalletConnectToRemoteNode[8].RemoteNodeHost] = ClassUtils.DateUnixTimeNowSecond();
                        }
                    }
                    ClassWalletObject.DisconnectWholeRemoteNodeSyncAsync(true, true);
                }
            }
            catch
            {
            }
            ClassWalletObject.InReceiveTransaction = false;
        }
예제 #12
0
        /// <summary>
        /// Open and connect the wallet.
        /// </summary>
        /// <returns></returns>
        private void OpenAndConnectWallet()
        {
            if (textBoxPasswordWallet.Text == "")
            {
#if WINDOWS
                ClassFormPhase.MessageBoxInterface(ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_CONTENT_TEXT"),
                                                   ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
#else
                MessageBox.Show(ClassFormPhase.WalletXiropht, ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_CONTENT_TEXT"),
                                ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NO_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
#endif
                return;
            }

            new Thread(async delegate()
            {
                try
                {
                    bool error = false;

                    string passwordEncrypted = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                                  textBoxPasswordWallet.Text, textBoxPasswordWallet.Text, ClassWalletNetworkSetting.KeySize);

                    ClassWalletObject.WalletDataDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                                               _walletFileData, passwordEncrypted, ClassWalletNetworkSetting.KeySize); // AES
                    if (ClassWalletObject.WalletDataDecrypted == ClassAlgoErrorEnumeration.AlgoError)
                    {
                        error = true;
                    }

                    if (error)
                    {
                        ClassWalletObject.WalletDataDecrypted = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael,
                                                                                                   _walletFileData, textBoxPasswordWallet.Text, ClassWalletNetworkSetting.KeySize); // AES
                    }

                    if (ClassWalletObject.WalletDataDecrypted == ClassAlgoErrorEnumeration.AlgoError)
                    {
#if WINDOWS
                        ClassFormPhase.MessageBoxInterface(
                            ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                            ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
                        MessageBox.Show(ClassFormPhase.WalletXiropht,
                                        ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                                        ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_WRONG_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
                        return;
                    }

                    var splitWalletFileDecrypted =
                        ClassWalletObject.WalletDataDecrypted.Split(new[] { "\n" }, StringSplitOptions.None);
                    string walletAddress = splitWalletFileDecrypted[0];
                    string walletKey     = splitWalletFileDecrypted[1];
                    if (!await ClassWalletObject.InitializationWalletConnection(walletAddress, textBoxPasswordWallet.Text,
                                                                                walletKey, ClassWalletPhase.Login))
                    {
                        MethodInvoker invoker = () => textBoxPasswordWallet.Text = "";
                        BeginInvoke(invoker);
#if WINDOWS
                        ClassFormPhase.MessageBoxInterface(
                            ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_CONTENT_TEXT"), ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_TITLE_TEXT"), MessageBoxButtons.OK,
                            MessageBoxIcon.Warning);
#else
                        MessageBox.Show(ClassFormPhase.WalletXiropht,
                                        ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_CONTENT_TEXT"), ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_TITLE_TEXT"), MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning);
#endif
                        return;
                    }

                    MethodInvoker invoke = () => textBoxPasswordWallet.Text = "";
                    BeginInvoke(invoke);

                    ClassWalletObject.ListenSeedNodeNetworkForWallet();

                    Stopwatch packetSpeedCalculator = new Stopwatch();
                    packetSpeedCalculator.Start();
                    if (await ClassWalletObject.WalletConnect.SendPacketWallet(ClassWalletObject.Certificate, string.Empty, false))
                    {
                        packetSpeedCalculator.Stop();
                        if (packetSpeedCalculator.ElapsedMilliseconds > 0)
                        {
                            Thread.Sleep((int)packetSpeedCalculator.ElapsedMilliseconds);
                        }
                        await ClassWalletObject.WalletConnect.SendPacketWallet(
                            ClassConnectorSettingEnumeration.WalletLoginType + "|" + ClassWalletObject.WalletConnect.WalletAddress, ClassWalletObject.Certificate, true);
                        _walletFileData   = string.Empty;
                        _fileSelectedPath = string.Empty;
                        invoke            = () => labelOpenFileSelected.Text = ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_LABEL_FILE_SELECTED_TEXT");
                        BeginInvoke(invoke);
                    }
                }
                catch
                {
#if WINDOWS
                    ClassFormPhase.MessageBoxInterface(
                        ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                        ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
                    MessageBox.Show(ClassFormPhase.WalletXiropht,
                                    ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_CONTENT_TEXT"),
                                    ClassTranslation.GetLanguageTextFromOrder("OPEN_WALLET_ERROR_MESSAGE_NETWORK_WRONG_PASSWORD_WRITTED_TITLE_TEXT"), MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
                }
            }).Start();
        }
예제 #13
0
        /// <summary>
        /// Start to listen incoming client.
        /// </summary>
        /// <returns></returns>
        public async Task StartHandleClientHttpAsync()
        {
            var isWhitelisted = true;

            if (ClassRpcSetting.RpcWalletApiIpWhitelist.Count > 0)
            {
                if (!ClassRpcSetting.RpcWalletApiIpWhitelist.Contains(_ip))
                {
                    ClassConsole.ConsoleWriteLine(_ip + " is not whitelisted.", ClassConsoleColorEnumeration.IndexConsoleRedLog, ClassConsoleLogLevelEnumeration.LogLevelApi);
                    isWhitelisted = false;
                }
            }

            int totalWhile = 0;

            if (isWhitelisted)
            {
                await Task.Run(() => MaxKeepAliveFunctionAsync()).ConfigureAwait(false);

                try
                {
                    while (_clientStatus)
                    {
                        try
                        {
                            using (NetworkStream clientHttpReader = new NetworkStream(_client.Client))
                            {
                                using (BufferedStream bufferedStreamNetwork = new BufferedStream(clientHttpReader, ClassConnectorSetting.MaxNetworkPacketSize))
                                {
                                    byte[] buffer = new byte[ClassConnectorSetting.MaxNetworkPacketSize];

                                    int received = await bufferedStreamNetwork.ReadAsync(buffer, 0, buffer.Length);

                                    if (received > 0)
                                    {
                                        string packet = Encoding.UTF8.GetString(buffer, 0, received);
                                        if (ClassRpcSetting.RpcWalletApiEnableXForwardedForResolver)
                                        {
                                            try
                                            {
                                                if (!GetAndCheckForwardedIp(packet))
                                                {
                                                    break;
                                                }
                                            }
                                            catch
                                            {
                                            }
                                        }
                                        packet = ClassUtility.GetStringBetween(packet, "GET /", "HTTP");
                                        packet = packet.Replace("%7C", "|"); // Translate special character |
                                        packet = packet.Replace(" ", "");    // Remove empty,space characters
                                        ClassConsole.ConsoleWriteLine("HTTP API - packet received from IP: " + _ip + " - " + packet, ClassConsoleColorEnumeration.IndexConsoleYellowLog, ClassConsoleLogLevelEnumeration.LogLevelApi);
                                        if (ClassRpcSetting.RpcWalletApiKeyRequestEncryption != string.Empty)
                                        {
                                            packet = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, packet, ClassRpcSetting.RpcWalletApiKeyRequestEncryption, ClassWalletNetworkSetting.KeySize);
                                            if (packet == ClassAlgoErrorEnumeration.AlgoError)
                                            {
                                                ClassConsole.ConsoleWriteLine("HTTP API - wrong packet received from IP: " + _ip + " - " + packet, ClassConsoleColorEnumeration.IndexConsoleRedLog, ClassConsoleLogLevelEnumeration.LogLevelApi);
                                                break;
                                            }
                                            ClassConsole.ConsoleWriteLine("HTTP API - decrypted packet received from IP: " + _ip + " - " + packet, ClassConsoleColorEnumeration.IndexConsoleYellowLog, ClassConsoleLogLevelEnumeration.LogLevelApi);
                                        }

                                        await HandlePacketHttpAsync(packet);

                                        break;
                                    }
                                    else
                                    {
                                        totalWhile++;
                                    }
                                    if (totalWhile >= 8)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        catch (Exception error)
                        {
                            ClassConsole.ConsoleWriteLine("HTTP API - exception error: " + error.Message, ClassConsoleColorEnumeration.IndexConsoleYellowLog, ClassConsoleLogLevelEnumeration.LogLevelApi);
                            break;
                        }
                    }
                }
                catch
                {
                }
            }
            CloseClientConnection();
        }
예제 #14
0
        /// <summary>
        /// Send a transaction from a selected wallet address stored to a specific wallet address target.
        /// </summary>
        /// <param name="getSeedNodeRandom"></param>
        /// <param name="walletAddress"></param>
        /// <param name="walletAddressTarget"></param>
        /// <param name="amount"></param>
        /// <param name="fee"></param>
        /// <param name="anonymous"></param>
        /// <returns></returns>
        private static async Task <string> SendWalletTransactionTokenAsync(string getSeedNodeRandom, string walletAddress, string walletAddressTarget, string amount, string fee, bool anonymous)
        {
            string tokenWallet = await GetWalletTokenAsync(getSeedNodeRandom, walletAddress);

            if (tokenWallet != RpcTokenNetworkNotExist)
            {
                string encryptedRequest = string.Empty;
                if (anonymous)
                {
                    encryptedRequest = ClassRpcWalletCommand.TokenAskWalletSendTransaction + "|" + tokenWallet + "|" + walletAddressTarget + "|" + amount + "|" + fee + "|1|" + (DateTimeOffset.Now.ToUnixTimeSeconds() + 1);
                }
                else
                {
                    encryptedRequest = ClassRpcWalletCommand.TokenAskWalletSendTransaction + "|" + tokenWallet + "|" + walletAddressTarget + "|" + amount + "|" + fee + "|0|" + (DateTimeOffset.Now.ToUnixTimeSeconds() + 1);
                }
                encryptedRequest = ClassAlgo.GetEncryptedResultManual(ClassAlgoEnumeration.Rijndael, encryptedRequest, walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey(), ClassWalletNetworkSetting.KeySize);
                string responseWallet = await ProceedTokenRequestAsync("http://" + getSeedNodeRandom + ":" + ClassConnectorSetting.SeedNodeTokenPort + "/" + ClassConnectorSettingEnumeration.WalletTokenType + "|" + walletAddress + "|" + encryptedRequest);

                ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletOnUpdateStatus(false);
                var responseWalletJson = JObject.Parse(responseWallet);
                responseWallet = responseWalletJson["result"].ToString();
                if (responseWallet != RpcTokenNetworkNotExist)
                {
                    responseWallet = ClassAlgo.GetDecryptedResultManual(ClassAlgoEnumeration.Rijndael, responseWallet, walletAddress + ClassRpcDatabase.RpcDatabaseContent[walletAddress].GetWalletPublicKey() + tokenWallet, ClassWalletNetworkSetting.KeySize);
                    if (responseWallet != ClassAlgoErrorEnumeration.AlgoError)
                    {
                        string walletTransaction = responseWallet;
                        if (responseWallet != RpcTokenNetworkNotExist)
                        {
                            var splitWalletTransaction = walletTransaction.Split(new[] { "|" }, StringSplitOptions.None);
                            if ((long.Parse(splitWalletTransaction[splitWalletTransaction.Length - 1]) + 10) - DateTimeOffset.Now.ToUnixTimeSeconds() < 60)
                            {
                                if (long.Parse(splitWalletTransaction[splitWalletTransaction.Length - 1]) + 10 >= DateTimeOffset.Now.ToUnixTimeSeconds())
                                {
                                    ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletBalance(splitWalletTransaction[1]);
                                    ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletPendingBalance(splitWalletTransaction[2]);
                                    ClassConsole.ConsoleWriteLine("Send transaction response " + splitWalletTransaction[0] + " from wallet address " + walletAddress + " of amount " + amount + " " + ClassConnectorSetting.CoinNameMin + " fee " + fee + " " + ClassConnectorSetting.CoinNameMin + " transaction hash: " + splitWalletTransaction[3] + " to target -> " + walletAddressTarget, ClassConsoleColorEnumeration.IndexConsoleYellowLog, ClassConsoleLogLevelEnumeration.LogLevelWalletObject);
                                    ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletOnSendTransactionStatus(false);
                                    return(splitWalletTransaction[0] + "|" + splitWalletTransaction[3]);
                                }
                                return(splitWalletTransaction[0] + "|expired_packet");
                            }
                        }
                        else
                        {
                            ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletOnSendTransactionStatus(false);
                            return(ClassRpcWalletCommand.SendTokenTransactionBusy + "|None");
                        }
                    }
                    else
                    {
                        ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletOnSendTransactionStatus(false);
                        return(ClassRpcWalletCommand.SendTokenTransactionBusy + "|None");
                    }
                }
            }

            ClassConsole.ConsoleWriteLine("Send transaction refused from wallet address " + walletAddress + " of amount " + amount + " " + ClassConnectorSetting.CoinNameMin + " fee " + fee + " " + ClassConnectorSetting.CoinNameMin + " to target -> " + walletAddressTarget, ClassConsoleColorEnumeration.IndexConsoleYellowLog, ClassConsoleLogLevelEnumeration.LogLevelWalletObject);
            ClassRpcDatabase.RpcDatabaseContent[walletAddress].SetWalletOnSendTransactionStatus(false);
            return(ClassRpcWalletCommand.SendTokenTransactionRefused + "|None");
        }