Esempio n. 1
0
        /// <summary>
        ///     Decrypt a packet according to wallet phase.
        /// </summary>
        /// <param name="packet"></param>
        /// <returns></returns>
        private string DecryptPacketWallet(string packet)
        {
            switch (WalletPhase)
            {
            case "":
                return(packet);

            case ClassWalletPhase.Restore:
            case ClassWalletPhase.Create:
                return(packet);

            case ClassWalletPhase.Login:
                return(packet);

            default:
                if (AesIvCertificate == null)
                {
                    using (PasswordDeriveBytes password = new PasswordDeriveBytes(WalletAddress + WalletPassword + WalletKey + ClassConnectorSetting.NETWORK_GENESIS_KEY, ClassUtils.GetByteArrayFromString(ClassUtils.FromHex((WalletAddress + WalletPassword + WalletKey + ClassConnectorSetting.NETWORK_GENESIS_KEY).Substring(0, 8)))))
                    {
                        AesIvCertificate   = password.GetBytes(ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE / 8);
                        AesSaltCertificate = password.GetBytes(16);
                    }
                }
                return(ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael, packet, ClassWalletNetworkSetting.KeySize, AesIvCertificate, AesSaltCertificate));    // AES
            }
        }
        /// <summary>
        ///     Load transMethodInvoker in cache.
        /// </summary>
        /// <param name="walletAddress"></param>
        /// <returns></returns>
        public static void LoadWalletCache(string walletAddress)
        {
            if (ListTransaction != null)
            {
                ListTransaction.Clear();
            }
            else
            {
                ListTransaction = new Dictionary <string, ClassWalletTransactionObject>();
            }
            if (!string.IsNullOrEmpty(walletAddress))
            {
                OnLoad = true;
                try
                {
                    Task.Factory.StartNew(() =>
                    {
                        if (Directory.Exists(
                                ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory +
                                                         WalletTransMethodInvokerCacheDirectory + walletAddress +
                                                         "\\")))
                        {
                            if (File.Exists(ClassUtility.ConvertPath(
                                                AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory +
                                                walletAddress + "\\" + WalletTransMethodInvokerCacheFileExtension)))
                            {
                                byte[] AesKeyIv = null;
                                byte[] AesSalt  = null;
                                using (var password = new PasswordDeriveBytes(
                                           Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                           Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey,
                                           ClassUtils.GetByteArrayFromString(ClassUtils.FromHex(
                                                                                 (Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletAddress +
                                                                                  Program.WalletXiropht.ClassWalletObject.WalletConnect.WalletKey)
                                                                                 .Substring(0, 8)))))
                                {
                                    AesKeyIv = password.GetBytes(
                                        ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE / 8);
                                    AesSalt = password.GetBytes(16);
                                }

                                var listTransactionEncrypted = new List <string>();
                                using (var fs = File.Open(
                                           ClassUtility.ConvertPath(AppDomain.CurrentDomain.BaseDirectory +
                                                                    WalletTransMethodInvokerCacheDirectory +
                                                                    walletAddress +
                                                                    "\\" + WalletTransMethodInvokerCacheFileExtension),
                                           FileMode.Open, FileAccess.Read, FileShare.Read))
                                    using (var bs = new BufferedStream(fs))
                                        using (var sr = new StreamReader(bs))
                                        {
                                            string line;
                                            while ((line = sr.ReadLine()) != null)
                                            {
                                                listTransactionEncrypted.Add(line);
                                            }
                                        }

                                if (listTransactionEncrypted.Count > 0)
                                {
                                    var line = 0;
                                    foreach (var transactionEncrypted in listTransactionEncrypted)
                                    {
                                        line++;
                                        var walletTransactionDecrypted =
                                            ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael,
                                                                         transactionEncrypted, ClassWalletNetworkSetting.KeySize, AesKeyIv,
                                                                         AesSalt);
                                        if (walletTransactionDecrypted != ClassAlgoErrorEnumeration.AlgoError)
                                        {
                                            var splitTransaction =
                                                walletTransactionDecrypted.Split(new[] { "#" },
                                                                                 StringSplitOptions.None);
                                            if (!ListTransaction.ContainsKey(splitTransaction[1]))
                                            {
                                                var splitBlockchainHeight = splitTransaction[7]
                                                                            .Split(new[] { "~" }, StringSplitOptions.None);

                                                var transactionObject = new ClassWalletTransactionObject
                                                {
                                                    TransactionType          = splitTransaction[0],
                                                    TransactionHash          = splitTransaction[1],
                                                    TransactionWalletAddress = splitTransaction[2],
                                                    TransactionAmount        =
                                                        decimal.Parse(
                                                            splitTransaction[3].ToString(Program.GlobalCultureInfo),
                                                            NumberStyles.Currency, Program.GlobalCultureInfo),
                                                    TransactionFee = decimal.Parse(
                                                        splitTransaction[4].ToString(Program.GlobalCultureInfo),
                                                        NumberStyles.Currency, Program.GlobalCultureInfo),
                                                    TransactionTimestampSend    = long.Parse(splitTransaction[5]),
                                                    TransactionTimestampRecv    = long.Parse(splitTransaction[6]),
                                                    TransactionBlockchainHeight =
                                                        splitBlockchainHeight[0].Replace("{", "")
                                                };
                                                ListTransaction.Add(splitTransaction[1], transactionObject);

                                                Program.WalletXiropht.UpdateLabelSyncInformation(
                                                    "On load transaction database - total transactions loaded and decrypted: " +
                                                    (ListTransaction.Count + ClassWalletTransactionAnonymityCache
                                                     .ListTransaction.Count));
                                            }
#if DEBUG
                                            else
                                            {
                                                Log.WriteLine("Duplicate anonymous transaction: " + walletTransactionDecrypted);
                                            }
#endif
                                        }

#if DEBUG
                                        else
                                        {
                                            Log.WriteLine("Wrong transaction at line: " + line);
                                        }
#endif
                                    }
                                }

                                listTransactionEncrypted.Clear();
                                Program.WalletXiropht.ClassWalletObject.TotalTransactionInSync =
                                    ListTransaction.Count;
                                AesKeyIv = null;
                                AesSalt  = null;
                            }
                            else
                            {
                                File.Create(ClassUtility.ConvertPath(
                                                AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory +
                                                walletAddress + "\\" + WalletTransMethodInvokerCacheFileExtension)).Close();
                            }
                        }
                        else
                        {
                            if (Directory.Exists(ClassUtility.ConvertPath(
                                                     AppDomain.CurrentDomain.BaseDirectory +
                                                     WalletTransMethodInvokerCacheDirectory)) ==
                                false)
                            {
                                Directory.CreateDirectory(ClassUtility.ConvertPath(
                                                              AppDomain.CurrentDomain.BaseDirectory +
                                                              WalletTransMethodInvokerCacheDirectory));
                            }

                            Directory.CreateDirectory(ClassUtility.ConvertPath(
                                                          AppDomain.CurrentDomain.BaseDirectory + WalletTransMethodInvokerCacheDirectory +
                                                          walletAddress));
                        }

                        Program.WalletXiropht.ClassWalletObject.TotalTransactionInSync = ListTransaction.Count;
                        OnLoad = false;
                    }, Program.WalletXiropht.WalletCancellationToken.Token,
                                          TaskCreationOptions.DenyChildAttach, TaskScheduler.Current).ConfigureAwait(false);
                }
                catch
                {
                    Program.WalletXiropht.ClassWalletObject.TotalTransactionInSync = 0;
                    ListTransaction.Clear();
                    OnLoad = false;
                }
            }
        }
Esempio n. 3
0
        public async Task <string> ReceivePacketFromSeedNodeAsync(string certificate, bool isSeedNode = false,
                                                                  bool isEncrypted = false)
        {
            try
            {
                if (ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY) // New Layer for receive packet.
                {
                    using (var bufferPacket = new ClassSeedNodeConnectorObjectPacket())
                    {
                        using (var _connectorStream = new NetworkStream(_connector.Client))
                        {
                            using (var bufferedNetworkStream = new BufferedStream(_connectorStream, ClassConnectorSetting.MaxNetworkPacketSize))
                            {
                                int received = await bufferedNetworkStream.ReadAsync(bufferPacket.buffer, 0, bufferPacket.buffer.Length);

                                if (received > 0)
                                {
                                    bufferPacket.packet = Encoding.UTF8.GetString(bufferPacket.buffer, 0, received);
                                    if (bufferPacket.packet != ClassSeedNodeStatus.SeedError && bufferPacket.packet != ClassSeedNodeStatus.SeedNone)
                                    {
                                        if (isEncrypted)
                                        {
                                            if (AesIvCertificate == null)
                                            {
                                                using (PasswordDeriveBytes password = new PasswordDeriveBytes(certificate, ClassUtils.GetByteArrayFromString(ClassUtils.FromHex(certificate.Substring(0, 8)))))
                                                {
                                                    AesIvCertificate   = password.GetBytes(ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE / 8);
                                                    AesSaltCertificate = password.GetBytes(16);
                                                }
                                            }
                                            if (bufferPacket.packet.Contains("*"))
                                            {
                                                if (!string.IsNullOrEmpty(MalformedPacket))
                                                {
                                                    bufferPacket.packet = MalformedPacket + bufferPacket.packet;
                                                    MalformedPacket     = string.Empty;
                                                }
                                                var splitPacket = bufferPacket.packet.Split(new[] { "*" }, StringSplitOptions.None);
                                                bufferPacket.packet = string.Empty;
                                                foreach (var packetEach in splitPacket)
                                                {
                                                    if (packetEach != null)
                                                    {
                                                        if (!string.IsNullOrEmpty(packetEach))
                                                        {
                                                            if (packetEach.Length > 1)
                                                            {
                                                                if (packetEach.Contains(ClassRemoteNodeCommand.ClassRemoteNodeRecvFromSeedEnumeration.RemoteSendTransactionPerId))
                                                                {
                                                                    bufferPacket.packet += packetEach.Replace("*", "") + "*";
                                                                }
                                                                else
                                                                {
                                                                    string packetDecrypt = ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael, packetEach.Replace("*", ""), ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE, AesIvCertificate, AesSaltCertificate);

                                                                    if (packetDecrypt.Contains(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode))
                                                                    {
                                                                        var packetNewSeedNode      = packetDecrypt.Replace(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode, "");
                                                                        var splitPacketNewSeedNode = packetNewSeedNode.Split(new[] { ";" }, StringSplitOptions.None);
                                                                        var newSeedNodeHost        = splitPacketNewSeedNode[0];
                                                                        var newSeedNodeCountry     = splitPacketNewSeedNode[1];
                                                                        if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(newSeedNodeHost))
                                                                        {
                                                                            ClassConnectorSetting.SeedNodeIp.Add(newSeedNodeHost, newSeedNodeCountry);
                                                                        }
                                                                        if (!ClassConnectorSetting.SeedNodeDisconnectScore.ContainsKey(newSeedNodeHost))
                                                                        {
                                                                            ClassConnectorSetting.SeedNodeDisconnectScore.Add(newSeedNodeHost, new Tuple <int, long>(0, 0));
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        bufferPacket.packet += packetDecrypt + "*";
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (!bufferPacket.packet.Contains(ClassRemoteNodeCommand.ClassRemoteNodeRecvFromSeedEnumeration.RemoteSendTransactionPerId))
                                                {
                                                    try
                                                    {
                                                        string packetDecrypt = ClassAlgo.GetDecryptedResult(ClassAlgoEnumeration.Rijndael, bufferPacket.packet, ClassConnectorSetting.MAJOR_UPDATE_1_SECURITY_CERTIFICATE_SIZE, AesIvCertificate, AesSaltCertificate);


                                                        if (bufferPacket.packet.Contains(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode))
                                                        {
                                                            var packetNewSeedNode      = packetDecrypt.Replace(ClassSeedNodeCommand.ClassReceiveSeedEnumeration.WalletSendSeedNode, "");
                                                            var splitPacketNewSeedNode = packetNewSeedNode.Split(new[] { ";" }, StringSplitOptions.None);
                                                            var newSeedNodeHost        = splitPacketNewSeedNode[0];
                                                            var newSeedNodeCountry     = splitPacketNewSeedNode[1];
                                                            if (!ClassConnectorSetting.SeedNodeIp.ContainsKey(newSeedNodeHost))
                                                            {
                                                                ClassConnectorSetting.SeedNodeIp.Add(newSeedNodeHost, newSeedNodeCountry);
                                                            }
                                                            if (!ClassConnectorSetting.SeedNodeDisconnectScore.ContainsKey(newSeedNodeHost))
                                                            {
                                                                ClassConnectorSetting.SeedNodeDisconnectScore.Add(newSeedNodeHost, new Tuple <int, long>(0, 0));
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (packetDecrypt != ClassAlgoErrorEnumeration.AlgoError)
                                                            {
                                                                bufferPacket.packet = packetDecrypt + "*";
                                                            }
                                                            else
                                                            {
                                                                if (MalformedPacket.Length - 1 >= int.MaxValue || (long)(MalformedPacket.Length + bufferPacket.packet.Length) >= int.MaxValue)
                                                                {
                                                                    MalformedPacket = string.Empty;
                                                                }
                                                                MalformedPacket += bufferPacket.packet;
                                                            }
                                                        }
                                                    }
                                                    catch
                                                    {
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (bufferPacket.packet == ClassSeedNodeCommand.ClassReceiveSeedEnumeration.DisconnectPacket)
                                    {
                                        _isConnected = false;
                                        return(ClassSeedNodeStatus.SeedError);
                                    }

                                    return(bufferPacket.packet);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                _isConnected = false;
                return(ClassSeedNodeStatus.SeedError);
            }

            return(ClassSeedNodeStatus.SeedNone);
        }